Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static ImmutableArray is not initialized

I have one internal static class MyLists with a static member:

internal static ImmutableArray<string> MyList = 
    new ImmutableArray<string> { "asd", "qwe" };

In another public test class Tests I have a MyTest function which selects and compares the list.

[TestClass]
public class MyTests {
  [TestMethod]
  public void TestMyLists() {
    var list = MyLists.MyList.Select(s => s + ".foo");
  }
}

But, I get the following error:

Additional information: The type initializer for 'TestMyLists' threw an exception.
Object reference not set to an instance of an object.

When I debug I see the static ImmutableArray as value = Uninitialized. Why?

like image 403
ditoslav Avatar asked Nov 16 '16 13:11

ditoslav


1 Answers

According to the docs on ImmutableArray, you should use the Create() method instead of using constructor for this type of array, like this:

internal static ImmutableArray<string> List = ImmutableArray.Create("asd", "qwe");

About the reason why, I will point you to the article Please welcome ImmutableArray by Immo Landwerth, where he describes:

The default value of ImmutableArray<T> has the underlying array initialized with a null reference. In this case it behaves the same way as an ImmutableArray<T> that has been initialized with an empty array, i.e. the Length property returns 0 and iterating over it simply doesn’t yield any values. In most cases this is the behavior you would expect. However, in some cases you may want to know that the underlying array hasn’t been initialized yet. For that reason ImmutableArray<T> provides the property IsDefault which returns true if the underlying array is a null reference. For example you can use that information to implement lazy initialization.

like image 189
Tatranskymedved Avatar answered Nov 06 '22 19:11

Tatranskymedved