Exploring the .NET CoreFX Part 15: Using Non-Generic Factory Classes to Enable Type Inference

This is part 15 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.
Advertisements

Exploring the .NET CoreFX Part 14: Inside Immutable Collections

This is part 14 of my Exploring the .NET CoreFX Series.

Back in 2013, Immo Landwerth and Andrew Arnott recorded a Going Deep video called Inside Immutable Collections which describes how and why System.Collections.Immutable is built the way it is. It’s great background material to understand System.Collections.Immutable.