Search code examples
c#inheritanceclonederived-classbase-class

How to create a List<I> containing instances of B, given instances of A (A derives from B and B implements I)?


See the following sample code.

public interface I
{
    int ID { get; set; }
}

public class B : I
{
    public int ID { get; set; }
    public string PropB { get; set; }
}

public class A : B
{
    public string PropA { get; set; }

    public IEnumerable<I> GetListOfBase()
    {
        // Attempt #1
        var list1 = new List<I>();
        B b1 = this as B;
        list1.Add(b1);

        // Attempt #2
        var list2 = new List<I>();
        B b2 = (B)this.MemberwiseClone();
        list2.Add(b2);


        return list1;
    }
}

private static void TestGetListOfBase()
{
    var a = new A() { ID = 1, PropA = "aaa", PropB = "bbb" };
    var list = a.GetListOfBase();
}

In both my attempts, the list contains instances of A. I need it to contain instances of B. I am trying to avoid creating a new B, then copying the properties of A to B (I assume that will work!).

EDIT: the reason I need a list of Bs is that later on each B is passed into NPoco (a .NET micro ORM, derived from PetaPoco). NPoco takes the name of the type and uses it to determine the DB table to map to. Therefore it is critically important that a variable of the correct type is passed to the method.


Solution

  • No, there is no way to "convert" instance of derived class to instance of base class. You have to create new instances of base class and copy properties.

    There are multiple ways of doing so including manually copy each property (works for small number of properties). This operation frequently it is called "mapping" (hopefully it will help with your search for tools).

    Note if you are fine with just having different type for list Enumerable.OfType<T>() or Enumerable.Cast<T>() followed by ToList() would solve it in single statement.