Type inference classes
suggest changeDevelopers can be caught out by the fact that type inference doesn’t work for constructors:
class Tuple<T1,T2>
{
public Tuple(T1 value1, T2 value2)
{
}
}
var x = new Tuple(2, "two"); // This WON'T work...
var y = new Tuple<int, string>(2, "two"); // even though the explicit form will.
The first way of creating instance without explicitly specifying type parameters will cause compile time error which would say:
Using the generic type ‘Tuple<T1, T2>’ requires 2 type arguments
A common workaround is to add a helper method in a static class:
static class Tuple
{
public static Tuple<T1, T2> Create<T1, T2>(T1 value1, T2 value2)
{
return new Tuple<T1, T2>(value1, value2);
}
}
var x = Tuple.Create(2, "two"); // This WILL work...
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents