I have a base class:
class MyBase
{
public int Id { get; set; }
public string CreatedBy { get; set; }
public DateTime CreateAt { get; set; }
}
There is a subclass with readonly properties inherited from the base class:
class MySub : MyBase
{
public string CreateAtStr{
get { return CreateAt.ToString("yyyy-MMM-dd", CultureInfo.InvariantCulture); }
}
}
I can only get results of MyBase type, I want them to be auto converted to MySub type.
How to do it? BTW: base class is entity class and sub class is for the view so it needs some customization.
You cannot convert a base class to a derived class, OOP doesn’t cover this case (simply because a base class instance is not a derived class instance).
You could on the other hand create new instances of
MySuband then use a mapping tool like AutoMapper (or perform it manually) to copy the values of all the base properties.I.e manual copying:
Edit:
In your specific case (using only existing public properties of the base class), and if you do not mind using a method instead of a property an alternative could be an extension method:
Now you do not need a derived class at all but can simply call
CreateAtStr()on instances of typeMyBase: