Is it possible to write an generic method with some types so that only one of them is specified when used?
something like this:
class Foo
{
public static TOut Bar<T1, T2, T3, TOut>(T1 t1, T2 t2, T3 t3)
{
TOut destination;
// other logic here
return destination;
}
}
To use it like this:
foo.Bar<TOut>()
Because the compiler understands T1 - T3 by arguments and it can be enough to specify only the TOut :)
It is not allowed in c#. The rule is so, you need to specify both generic arguments or none of the them if inference is possible. By the way, when compiler detects type based on the specified value it is called Type Inference.
For achieving the desired result, I have two offers for you.
1) You can change the design of your class in that way:
public class Foo<T1, T2, T3>
{
T1 t1;
T2 t2;
T3 t3;
public Foo(T1 t1, T2 t2, T3 t3)
{
this.t1 = t1;
this.t2 = t2;
this.t3 = t3;
}
public TOut Bar<TOut>()
{
...
}
}
public class Foo
{
public static Foo<T1, T2, T3> CreateFoo<T1, T2, T3>(T1 t1, T2 t2, T3 t3)
{
return new Foo<T1, T2, T3>(t1, t2, t3);
}
}
And then call Bar in that way:
var foo = Foo.CreateFoo(4,"", "");
var result = foo.Bar<string>();
By the way, I implemented CreateFoo method, because constrcutors are not supporting type inference.
2) Or as a second approach I can offer you to make use of out:
class Foo
{
public static void Bar<T1, T2, T3, TOut>(T1 t1, T2 t2, T3 t3, out TOut tOut)
{
//...
}
}
And then use it so:
Foo.Bar(5, 4, 6, out string x);
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