Vilx-
Vilx-

Reputation: 106904

How to call a generic method with type constraints when the parameter doesn't have these constraints?

class A { }
interface I { }
void GenericStuff<T>(T x) { }
void SpecificStuff<T>(T x) where T : A, I { }

void Start<T>(T x)
{
    if (x is A && x is I)
        SpecificStuff(x); // <---- Wrong type
    else
        GenericStuff(x);
}

I've got the situation illustrated above. In method Start() I get a single parameter x and depending on it's type I want to call either the GenericStuff() or the SpecificStuff() method. Naturally, the type constraints prevent me from doing so, and since there are two of them, I cannot get around them by casting.

Is there any way (short of reflection) to accomplish this?

Upvotes: 2

Views: 72

Answers (1)

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174289

You can use dynamic. While this is more or less glorified reflection, it looks much nicer:

void Start<T>(T x)
{
    if (x is A && x is I)
        SpecificStuff((dynamic)x);
    else
        GenericStuff(x);
}

Please note:
If, at a later point, you change the type constraints of SpecificStuff to contain a third interface and you forget to update your if accordingly, you will get runtime exceptions and not compile time errors.

Upvotes: 5

Related Questions