ImmutableArrays should be initialized

With ImmutableArray<T>, Microsoft provides immutable collection that can be preferable over other read-only and/or immutable collections, depending on your scenario. Fundamental to its design, is it being a struct.

To prevent null dereference exceptions, these immutable arrays most be properly be initialized, as there default initialization will result in NullReferenceException’s being thrown when accessed.

using System.Collections.Immutable;

namespace ImmutableArrays;

public class NonCompliant
{
	public ImmutableArray<int> Init { get; init; } // Noncompliant

	public ImmutableArray<int> Default { get; set; } = default; // Noncompliant

	public ImmutableArray<int> Default_T { get; set; } = default(ImmutableArray<int>); // Noncompliant
}

public class Compliant
{
	public Compliant(ImmutableArray<int> ctor)
	{
		Ctor = ctor;
	}

	public ImmutableArray<int> Ctor { get; }

	public ImmutableArray<int> Initialized { get; init; } = [];

	public ImmutableArray<int> Empty { get; init; } = ImmutableArray<int>.Empty;

	public required ImmutableArray<int> Required { get; init; }
}

public class CompliantWitDefaultConstructor(ImmutableArray<int> defaultCtor)
{
	public ImmutableArray<int> DefaultCtor { get; } = defaultCtor;

	public ImmutableArray<int> Initialized { get; init; } = [];

	public ImmutableArray<int> Empty { get; init; } = ImmutableArray<int>.Empty;

	public required ImmutableArray<int> Required { get; init; }
}

Thanks @Corniel .
I added this to our backlog.

1 Like

As an extra: All assigments to ImmutableArray<T> with default and default(T) should be flagged. I think this can/should be part of this rule.

1 Like

Acked!

1 Like