Reputation: 1107
So what I have is a generic Method with multiple generic types.
Now I'd like to call this Method this way (using the types of a and b and just specifying the return type):
class Example
{
T1 GenericMethod<T1, T2, T3>(T2 parameter1, T3 parameter2)
{
T1 returnValue = default(T1);
// ... Do something with returnType, parameter1 and parameter2
return returnValue;
}
void AccessGenericMethod()
{
var a = new Foo1();
var b = new Foo2();
var result = GenericMethod<ReturnType>(a, b); // doesn't work
}
}
And i would like to avoid to call GenericMethod
this way
var result GenericMethod<ReturnType, Foo1, Foo2>(a, b);
Upvotes: 3
Views: 6386
Reputation: 1
I found a solution
class Example
{
T1 GenericMethod<T1, T2, T3>(T2 parameter1, T3 parameter2, out T1 returnValue)
{
returnValue = default(T1);
// ... Do something with returnType, parameter1 and parameter2
return returnValue = new T1();
}
void AccessGenericMethod()
{
var a = new Foo1();
var b = new Foo2();
GenericMethod(a, b, out ReturnType result1); // work!
ReturnType result2 = GenericMethod(a, b, out result2);
}
}
Upvotes: -1
Reputation: 12215
In C#, there is no partial type inference: You must either specify all or none of the generic arguments, but the latter only works if the compiler is able to infer all types from context. Return types cannot be infered (except for some special cases such as lambdas), so what you want to do is not possible.
Two workarounds:
A: Move T1
from the method to the class
class Example<T1>
{
T1 GenericMethod<T2, T3>(T2 parameter1, T3 parameter2)
B: Replace T2
and T3
by object
class Example
{
T1 GenericMethod<T1>(object parameter1, object parameter2)
Upvotes: 4