superche
superche

Reputation: 773

Auto create subclass instance from its baseclass instance

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.

Upvotes: 2

Views: 2318

Answers (1)

BrokenGlass
BrokenGlass

Reputation: 160862

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 MySub and then use a mapping tool like AutoMapper (or perform it manually) to copy the values of all the base properties.

I.e manual copying:

List<MyBase> items = ...
List<MySub> subs = items.Select( x=> new MySub() 
                         { 
                           Id = x.Id, 
                           CreatedBy = x.CreatedBy, 
                           CreatedAt = x.CreatedAt
                         })
                        .ToList();

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:

public static class FooExtensions
{
    public static string CreateAtStr(this MyBase myBase)
    {
       return myBase.CreateAt.ToString("yyyy-MMM-dd", CultureInfo.InvariantCulture); 
    }
}

Now you do not need a derived class at all but can simply call CreateAtStr() on instances of type MyBase:

MyBase myBase = new MyBase();
string createdAt = myBase.CreateAtStr();

Upvotes: 4

Related Questions