Say I have this method
public void test(IList<AvaliableFeaturesVm> vm)
{
}
I have this class that inherits my base class
public class TravelFeaturesVm : AvaliableFeaturesVm
{
}
how do I pass it into method “test”. If test only accepted one AvaliableFeatureVm object it would let me pass in a TravelFeaturesVm object but since they are in a collection it does not let me.
As of C# 4, you can do this if you change the signature of the first call to:
This is due to generic covariance which was introduced in C# 4.
IEnumerable<T>is covariant inTin C# 4, butIList<T>is invariant, so it won’t as-is. If you’re not using C# 4, this won’t work anyway.This is assuming that all your method needs to do is iterate over the collection. If it needs to modify the collection, then it wouldn’t be safe to pass in a list of the subtype anyway – because the method could try to add either an instance of the base class, or of a different subtype.
Another alternative is to make the method itself generic:
Of course, this has its own limitations – in particular, again you won’t be able to write:
… although you can do:
as the constraint ensures that there’s an appropriate conversion from
TtoAvailableFeaturesVm.For more on generic variance, see Eric Lippert’s blog posts.