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.
Generic Type Parameters (C# Programming Guide) In a generic type or method definition, a type parameters is a placeholder for a specific type that a client specifies when they instantiate a variable of the generic type.
In a generic type or method definition, a type parameter is a placeholder for a specific type that a client specifies when they create an instance of the generic type. A generic class, such as GenericList<T> listed in Introduction to Generics, cannot be used as-is because it is not really a type; it is more like a blueprint for a type.
Consider using T as the type parameter name for types with one single letter type parameter. Consider indicating constraints placed on a type parameter in the name of parameter. For example, a parameter constrained to ISession may be called TSession.
To use GenericList<T>, client code must declare and instantiate a constructed type by specifying a type argument inside the angle brackets. The type argument for this particular class can be any type recognized by the compiler. Any number of constructed type instances can be created, each one using a different type argument, as follows:
You can use the dynamic
keyword like this:
public void Foo<T>(T parameter)
{
dynamic p = parameter
otherObject.Bar(p);
}
What's happening is that the resolution of the call to otherObject.Bar
is being made at run-time, because one of the parameters has a type of dynamic
. Assuming that T
is 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 T
is not a class.
public void Foo<T>(T parameter)
{
otherObject.Bar<object>(parameter);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With