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.