user3879250
user3879250

Reputation:

Why am I getting an 'Invalid Parameters' error when the generic type constraints are the same?

In the code below, I am getting an error at 'action(u)', "Invalid Parameters", even though the type constraints on the generics are the same. Why is that and what can I do?

        public class Test<T> : IDoStuff where T : SampleA
        {

            Action<T> action;

            void DoStuff<U>(U u) where U : SampleA
            {
                action(u);
            }

        }

Upvotes: 4

Views: 95

Answers (2)

adjan
adjan

Reputation: 13684

U and T are not the same, even if they are derived from the same base class.

Upvotes: 2

Eric J.
Eric J.

Reputation: 150198

Let's say that SampleA represents animals, and you do this

public class Bird :  SampleA { }

public class Dog :  SampleA { }

Test<Bird> b = new Test<Bird>();
b.DoStuff<Dog>();

The field action now knows how to act on a Bird, but not on the Dog you passed it, even if they share an interface and common base class.

You can make this work by changing this line

Action<T> action;

to

Action<SampleA> action;

Upvotes: 4

Related Questions