2

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.

superche
  • 753
  • 3
  • 9
  • 21
  • Duplicate of [this](http://stackoverflow.com/questions/124336/a-way-of-casting-a-base-type-to-a-derived-type)? – Sumo Aug 24 '11 at 02:25
  • 1
    You should really revise your question to be a bit more to the point. In it's current form, it's quite difficult to comprehend what exactly you're wanting to achieve. – Allen Gammel Aug 24 '11 at 02:27

1 Answers1

4

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();
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335