John Cale
John Cale

Reputation: 13

Why can't I reference a list of a child class in a function expecting a list of the parent class?

public class A {
    public int ID {get;set;}
    public List<int> Things {get;set}
}

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

public static FillListAThings(ref List<A> lstA){
 // ...
 // code to fill the Things list in each A of lstA with bulk call to database containing all A's IDs from lstA
 // ...
}

public static GetBList(){
  var lstB = new List<B>();

  // ...
  // Fill B list, get IDs and names
  // ...

  // ERROR here, since ref List<B> cannot be converted to a ref List<A>
  FillListAThings(ref lstB); 

}

I can understand not being able to pass a ref List A to a function expecting ref List B, since there would be missing members in the class, but why isn't this possible? I can't cast it as List A through LINQ either, since then it becomes a throw-away variable that can't be referenced.

My current workaround is to cast to a temporary variable of a List A, send that to the function to fill, then copy the properties back to the original list by crossing on their IDs.

// workaround
var tmpListA = lstB.Cast<A>().ToList();
FillListAThings(ref tmpListA);
foreach(var b in lstB)
{
    var a = tmpListA.Where(x => x.ID == b.ID);
    // ... 
    // code to copy properties
    // ...
}

Upvotes: 1

Views: 202

Answers (1)

NightOwl888
NightOwl888

Reputation: 56869

You can, but you need to widen your method signature to accept all List<T> types that implement A, not just List<A> itself.

public static void FillListAThings<T>(ref List<T> lstA) where T : A
{
    // ...
    // code to fill the Things list in each A of lstA with bulk call to database containing all A's IDs from lstA
    // ...
}

Upvotes: 3

Related Questions