Here’s what I am trying to write:
public void Foo<T>(T parameter) {
otherObject.Bar<T>(parameter);
}
The signature of the Bar() method is:
public void Bar<T>(T parameter) where T: class
So I get a compile error because the T in Foo’s signature doesn’t have the same constraint. Unfortunately I can’t write:
public void Foo<T>(T parameter) where T: class {
otherObject.Bar<T>(parameter);
}
because Foo is implementing a method defined in an external interface. Question is:
Can I somehow transpose the T within the method Foo before calling Bar. (Note, I can be sure that T always will be a class – I just need to get past the compiler).
The only way I have found is using reflection but I wonder if there is a simpler trick I’m missing.
You can use the
dynamickeyword like this:What’s happening is that the resolution of the call to
otherObject.Baris being made at run-time, because one of the parameters has a type ofdynamic. Assuming thatTis a reference type, the resolution will succeed.Granted, this ultimately uses reflection (as you’ve indicated), but the syntax is probably better than what you’re using.
Of course, this will give you a run-time error in the event that
Tis not a class.