Consider
public class Tuple<T1, T2>
{
public Tuple(T1 v1, T2 v2)
{
V1 = v1;
V2 = v2;
}
public T1 V1 { get; set; }
public T2 V2 { get; set; }
}
public static class Tuple
{
// MAGIC!!
public static Tuple<T1, T2> New<T1, T2>(T1 v1, T2 v2)
{
return new Tuple<T1, T2>(v1, v2);
}
}
Why does the part labeled “MAGIC” in the above work? It allows syntax like
Tuple.New(1, "2") instead of new Tuple<int, string>(1, "2"), but … how and why?
Why do I not need Tuple.New<int,string>(1, "2") ??
This is called generic type inference and it works for generic methods only. You can pass instances of whatever types you want as the arguments to
Newand the compiler infers that you mean to return the particular generic Tuple that matches the arguments likeTuple<int, string>…