Why is ImmutableList<T> a class but ImmutableArray<T> a struct?

585 views Asked by At

When you read the documentation for ImmutableArray and ImmutableList, you can see that:

  • ImmutableArray<T> has been implemented as a struct
  • ImmutableList<T> has been implemented as a class

Question:

Can you explain why such design decision?

Especially, why ImmutableArray<T> is a struct.

After all, System.Array is a class so, why it isn't the case for ImmutableArray<T>?

1

There are 1 answers

1
paulsm4 On BEST ANSWER

This article sheds a bit of light on the decision to make .Net ImmutableArray a "struct" instead of a class:

Choosing Between Class and Struct

✔️ CONSIDER defining a struct instead of a class if instances of the type are small and commonly short-lived or are commonly embedded in other objects.

❌ AVOID defining a struct unless the type has all of the following characteristics:

  • It logically represents a single value, similar to primitive types (int, double, etc.).
  • It has an instance size under 16 bytes.
  • It is immutable.
  • It will not have to be boxed frequently.

In all other cases, you should define your types as classes.

See also: