Recently I read about[1] this handy little trick to get around the ‘problem’ of constructors for generic types in C# not supporting type inference. For example if we had, say, a generic type defined as:
public class Pair<T1, T2>
{
public Pair(T1 first, T2 second) { ... }
...
}
Then to create an instance of this class would normally use something like:
var pair = new Pair<int, string>(10, "value");
This is a little cumbersome as always need to specify the type arguments even though its fairly obvious from the values what the types are. One way around this is to define a static class with a static generic method that can create a new Pair<T1, T2> instance:
public static class Pair
{
public static Pair<T1, T2> Of<T1, T2>(T1 first, T2 second)
{
return new Pair<T1, T2>(first, second);
}
}
Then to create an instance can now use:
var pair = Pair.Of(10, "value");
This same pattern is implemented in .NET 4 for the Tuple types, e.g. for a 2-tuple (or pair), to create via constructor would use:
var tuple = new Tuple<int, string>(10, "value");
or using the static Tuple class:
var tuple = Tuple.Create(10, "value");
Links:
- C# in Depth, Second Edition, Jon Skeet, Manning Publications Co., ISBN 978-1-935182-47-4. Now in third edition.