Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting List of derived class to List of base class still returning objects of derived class

I have the following code:

public class BaseClass
{
    public string A { get; set; }
}

public class DerivedClass : BaseClass
{
    public string B { get; set; }
}


List<DerivedClass> _derivedClass = new List<DerivedClass>() 
                                       { 
                                           new DerivedClass() 
                                             { A = "test1",
                                               B = "test2"
                                             }
                                       }; 

List<BaseClass> _baseClass = _derivedClass.Cast<BaseClass>.ToList();

The code compiles without any error, however, I expected _baseClass to only contain Property A (object of type BaseClass), but it's return both A and B properties (objects of type DerivedClass). What am I missing and what's the correct way to convert a List of a derived class to a list of its base class?

Thank you.

like image 346
Sam Dingo Avatar asked Dec 16 '22 14:12

Sam Dingo


1 Answers

What am I missing and what's the correct way to convert a List of a derived class to a list of its base class?

The list still contains instances of the DerivedClass, but they are being used as references to the BaseClass.

Any consumer of this API will not know this, however, so they would see this as BaseClass elements.

This is common, and typically the correct approach. If you needed to actually convert the instances to BaseClass instances (which is likely not necessary), you would need to actually make new BaseClass instances from the DerivedClass members, ie:

List<BaseClass> _baseClass = _derivedClass.Select(dc => new BaseClass {A = dc.A}).ToList();

That is typically not necessary, and your current approach is likely fine. The Liskov substitution principle states that any DerivedClass should be usable in any situation as a BaseClass, which means just returning the list as you did should be fine.

like image 131
Reed Copsey Avatar answered Mar 30 '23 00:03

Reed Copsey