Published: 2015-02-18
This is part 15/17 of my Exploring the .NET CoreFX series.
While C# supports type inference for generic methods, it does not support type inference for constructors. In other words, while this code works:
public class FooFactory
{
public static Foo<T> Create<T>(T value)
{
return new Foo<T>(value);
}
}
var myObj = FooFactory.Create(212);
This code does not:
public class Foo<T>
{
private readonly T field;
public Foo(T value) { field = value; }
}
var obj = new Foo(212); // DOES NOT WORK
For more background on why this is, see this StackOverflow post.
Because of this, every generic type in System.Collections.Immutable includes a factory class of the same name which makes construction more convenient. For example:
// Using the generic class which requires explicitly-specified types
var l = ImmutableList<int>.Empty.Add(1);
// Using the factory class to use inferred types
var l = ImmutableList.Create(1);
The same trick is also used with System.Tuple.
Recommendations
- If you author a generic class, consider also providing a factory class with generic methods to enable type inference.