2
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?

Vilx-
  • 104,512
  • 87
  • 279
  • 422

1 Answers1

5

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.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
  • Not bad, I like it! If there's nothing better, I'm accepting this! – Vilx- Apr 04 '13 at 10:39
  • @Vilx-: I don't think there is anything better, because compile time overload resolution doesn't take type parameters into account. And you can't even define a method with the same parameters but different type constraints. – Daniel Hilgarth Apr 04 '13 at 10:41
  • Well, but the method names are already different. So overload resolution should have no problems with picking the right method, right? I just need to convince it that the parameter is of the right type. – Vilx- Apr 04 '13 at 10:46
  • @Vilx-: Yeah, but because you can't do that - a variable can't have two types - I experimented with overload resolution. – Daniel Hilgarth Apr 04 '13 at 10:47