chobo2
chobo2

Reputation: 85835

How to pass a collection of objects into a method that takes in collection of base objects?

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.

Upvotes: 1

Views: 250

Answers (3)

Matthias
Matthias

Reputation: 16209

You can make it generic:

public void test<T>(IList<T> vm) where T : AvaliableFeaturesVm
{

}

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1502126

As of C# 4, you can do this if you change the signature of the first call to:

public void test(IEnumerable<AvaliableFeaturesVm> vm)
{
}

This is due to generic covariance which was introduced in C# 4. IEnumerable<T> is covariant in T in C# 4, but IList<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:

public void test<T>(IList<T> vm) where T : AvaliableFeaturesVm

Of course, this has its own limitations - in particular, again you won't be able to write:

vm.Add(new AvailableFeaturesVm());

... although you can do:

AvailableFeaturesVm first = vm[0];

as the constraint ensures that there's an appropriate conversion from T to AvailableFeaturesVm.

For more on generic variance, see Eric Lippert's blog posts.

Upvotes: 3

davogotland
davogotland

Reputation: 2777

declare your collection to be a collection of AvaliableFeaturesVm. this will allow you to put TravelFeaturesVm-objects in the collection, and it will allow you to pass the collection to your method :)

Upvotes: 2

Related Questions