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.


  • If you author a generic class, consider also providing a factory class with generic methods to enable type inference.

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.

Exploring the .NET CoreFX Part 13: ImmutableList is an AVL Tree

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

Most implementations of IList, including System.Collections.Generic.List, are dynamic arrays. System.Collections.Immutable.ImmutableList is different — it is an AVL tree. This results in significantly different performance characteristics:

  List ImmutableList
Indexing O(1) O(log n)
Append O(1) average, O(n) worst-case O(log n)
Insert at arbitrary index O(n) O(log n)
Remove O(n) O(log n)
Memory layout Contiguous for value types Non-contiguous

The data structure behind ImmutableList was likely chosen so that modifications to the list are non-destructive and require minimal data copying.

Here’s a visual representation of what List and ImmutableList look like behind the scenes:

List ImmutableList
List l = new List();
ImmutableList l = ImmutableList.Create();
l = l.Add(1);
l = l.Add(2);
l = l.Add(3);
l = l.Add(4);

Exploring the .NET CoreFX Part 12: Aggressive Inlining

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

In C++, the inline keyword allows a developer to provide a hint to the compiler that a particular method should be inlined. C# has the identical ability but uses an attribute instead:

internal class SecurePooledObject<T>

    internal bool IsOwned<TCaller>(ref TCaller caller)
        where TCaller : struct, ISecurePooledObjectUser
        return caller.PoolUserId == _owner;

In System.Collections.Immutable, this attribute is used highly selectively — only once, in fact.


  • In rare cases, consider using MethodImpl(MethodImplOptions.AggressiveInlining) to suggest to the .NET runtime that a particular method should be inlined.

Exploring the .NET CoreFX Part 11: Code Contracts

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

In 2008, Microsoft Research published Code Contracts, which provide a language-agnostic way to express coding assumptions in .NET programs. The assumptions take the form of pre-conditions, post-conditions, and object invariants.

Here is a simple example of code which uses Code Contracts:

using System.Diagnostics.Contracts;

public class StringUtils
    internal static string Append(string s1, string s2)
        Contract.Requires(s1 != null);
        Contract.Requires(s2 != null);
        Contract.Ensures(Contract.Result<string>() != null);
        return s1 + s2;

Code Contracts assertions are not limited to runtime enforcement. They may instead be enforced by compile-time static analysis. For example, it is very simple to annotate methods with Code Contracts, set up a continuous integration (CI) server to perform static analysis, and fail the build if there are any failed assertions. This gives us the best of both worlds: a guarantee our code enforces our assumptions with essentially zero runtime penalty.

By design, Code Contracts are not enforced unless the appropriate tools are configured to check them. For this reason they are usually not appropriate for parameter validation on public methods; there is still the need for traditional parameter validation. However you can combine traditional parameter validation on public methods with Code Contract-based assertions for internal methods as follows:

public class StringUtils
    // This is the method that external callers would use, as we can't
    // guarantee they will enforce Code Contract checking
    public static string Append(string s1, string s2)
        if (s1 == null)
            throw new ArgumentNullException("s1");
        if (s2 == null)
            throw new ArgumentNullException("s2");
        // The Code Contracts static analyzer is quite clever and it
        // realizes that the AppendInternal pre-conditions are satisfied
        // due to the above two statements, so no Contract.Assert()s
        // are required.
        return AppendInternal(s1, s2);

    // This is the method that other code in this assembly would use,
    // as we can guarantee that this code is checked at compile-time
    // with the Code Contracts static analyzer
    internal static string AppendInternal(string s1, string s2)
        Contract.Requires(s1 != null);
        Contract.Requires(s2 != null);
        Contract.Ensures(Contract.Result<string>() != null);
        return s1 + s2;

You can write Code Contracts assertions with just the .NET 4.5 SDK installed, but they will not be enforced. To enforce them at compile-time within Visual Studio:

  1. Install the Code Contracts for .NET extension using NuGet:
    Code Contracts for .NET
  2. Restart Visual Studio
  3. Open up the Project Properties dialog and click on the Code Contracts tab
  4. Click “Perform Static Contract Checking”
    Code Contracts Project Properties

System.Collections.Immutable uses Code Contracts only to express post-conditions and object invariants, never to validate pre-conditions. This is presumably to integrate well with client code which uses Code Contracts.

For more information on Microsoft Code Contracts, please read:


  1. Liberally annotate all methods with Code Contracts post-conditions and object invariants.
  2. If you can guarantee that a method will be called only by code that you control (e.g. internal methods), use Code Contracts to enforce pre-conditions. If you cannot, use traditional parameter validation.
  3. Integrate Code Contracts static code analysis into your CI pipeline, and fail the build on any warnings.

Exploring the .NET CoreFX Part 10: Performance Tuning Enumeration

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

The .NET Core’s System.Collections.Immutable.ImmutableArray provides two enumerators. The first has been highly tuned for speed, and the second is a fallback for compatibility when it is required.

The high-performance enumerator uses the following performance optimizations:

  1. The enumerator is a struct, rather than a class, so that it is stack-allocated rather than heap-allocated.
  2. The enumerator does not implement IEnumerator or IEnumerator, as this would require it to implement IDisposable. By not implementing IDisposable the iterator will inline during foreach loops..
  3. The enumerator does not use range checks in Enumerator.Current; it requires on .NET’s array range checks to throw an exception instead.

The high-performance enumerator is called ImmutableArray.Enumerator, which is returned by ImmutableArray.GetEnumerator():

public Enumerator GetEnumerator()
    return new Enumerator(this.array);

Note that this method is not defined by any interface ImmutableArray implements, but it will be used by foreach. This is because foreach is pattern-based rather than interface-based. What this means is that foreach does not require an object to implement IEnumerable as long as it implements a method named GetEnumerator(). Similarly, the returned object is not required to implement IEnumerator as long as it implements a Current property and a MoveNext() method.

The result of all this work is that foreach over an ImmutableArray is just as efficient as a hand-written for loop.


  1. To improve the performance of foreach, consider writing a specialized, struct-based enumerator in addition to the traditional one.

Exploring the .NET CoreFX Part 9: Immutable Collections and the Builder Pattern

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

Using the builder pattern to allow for easier construction of immutable objects is well-known.

The .NET Core’s immutable collections assembly, System.Collections.Immutable, also uses the builder pattern, but for a slightly different reason: to improve the performance of making many changes to the collection. This is possible because, unlike the immutable collection itself, the builder pattern does not need to maintain the immutable collection’s invariants after each modification. The builder pattern merely needs to reestablish the invariants of the immutable collection upon the publishing of the results.

Consider this code:

ImmutableArray<int> array = new ImmutableArray<int>();
for (int i = 1; i <= 100; ++i)
    array = array.Add(i);
// array now contains [1..100]

On each iteration of the loop, array must be a valid ImmutableArray. This will lead to a large number of reallocations and memory copies in order to maintain this requirement.

However, if the above code were replaced with this, it would be far more efficient:

ImmutableArray<int>.Builder builder = new ImmutableArray<int>().ToBuilder();
for (int i = 1; i <= 100; ++i)
ImmutableArray<int> array = builder.ToImmutable();
// array now contains [1..100]

This is also the pattern used by String and StringBuilder.

The .NET Core also uses a nice trick of separating ImmutableArray.Builder, an inner class with a substantial amount of code, into its own file by using partial classes:

// ImmutableArray`1.cs
/// <summary>
/// A readonly array with O(1) indexable lookup time.
/// </summary>
/// <typeparam name="T">The type of element stored by the array.</typeparam>
public partial struct ImmutableArray<T> : IReadOnlyList<T>, IList<T>, IEquatable<ImmutableArray<T>>, IImmutableList<T>, IList, IImmutableArray, IStructuralComparable, IStructuralEquatable

// ImmutableArray`1+Builder.cs
public partial struct ImmutableArray<T>
    /// <summary>
    /// A writable array accessor that can be converted into an <see cref="ImmutableArray{T}"/>
    /// instance without allocating memory.
    /// </summary>
    [DebuggerDisplay("Count = {Count}")]
    public sealed class Builder : IList<T>, IReadOnlyList<T>


  1. Immutable objects are often highly valuable. Consider making your objects immutable and implementing the builder pattern.