Exploring the .NET CoreFX Part 15: Using Non-Generic Factory Classes to Enable Type Inference
Exploring the .NET CoreFX .net core csharp system.collections.immutable
Published: 2015-02-18
Exploring the .NET CoreFX Part 15: Using Non-Generic Factory Classes to Enable Type Inference

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:

1
2
3
4
5
6
7
8
9
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:

1
2
3
4
5
6
7
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:

1
2
3
4
// 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.