I have an abstract parent class which child classes that inherit from it. I have another class that contains many List<> types of the different child classes. I then have a method in another class that takes a parameter of List<ParentType> and just calls the methods that are declared abstract.
I’m having a problem using List<T>.Cast<T2> on the lists of the child classes. I’m getting the error:
System.Linq.Enumerable.Cast(System.Collections.IEnumerable)’ is a ‘method’, which is not valid in the given context
Does anybody know how to fix this error? Or do I have to reconstruct a list of type List<ParentType> and recast each item individually?
What I’m trying to do:
public abstract class P {
public int num;
public abstract double addSections();
}
public class A : P {
public int num2;
public A(int r, int n) {
num = r;
num2 = n;
}
public double addSections() { return (double)num + (double)num2; }
}
public class B : P {
public double g;
public B(int r, double k) {
num = r;
g = k;
}
public double addSections() { return (double)num + g; }
}
public class MyClass {
public MyClass() {
List<A> listA;
List<B> listB;
//...
helper(listA.Cast<P>()); //doesn't work
helper(listB.Cast<P>().ToList()); //doesn't work either
}
public void helper(List<P> list) {
//...
}
}
In lieu of actually seeing your code so we can fix it, how about changing the method instead:
Or if you’re using C# 4 and .NET 4, this should be fine, as
IEnumerable<T>is covariant inTin .NET 4.Do you really need the method to accept a
List<ParentType>? After all, if you’re going to call:and pass that into the method, then you’ve got two entirely separate lists by that point anyway.
By the way, another effect of the covariant of
IEnumerable<T>is that in .NET 4 you can avoid theCastcall and just call:EDIT: Now that you’ve posted your code, it’s simply a matter of not calling the
Castmethod as a method: