Type inference (classes) C# with Example



Type inference (classes) C# with Example

Developers can be caught out by the fact that type inference doesn't work for constructors: 
class Tuple 
{ 
public Tuple(T1 value1, T2 value2) 
{ 
} 
} 
var x = new Tuple(2, "two"); // This WON'T work... 
var y = new Tuple(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' requires 2 type arguments 
A common workaround is to add a helper method in a static class: 
static class Tuple 
{ 
public static Tuple Create(T1 value1, T2 value2) 
{ 
return new Tuple(value1, value2); 
} 
} 
var x = Tuple.Create(2, "two"); // This WILL work... 

0 Comment's

Comment Form

Submit Comment