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?
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 anImmutableArray<T>
that has been initialized with an empty array, i.e. theLength
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 reasonImmutableArray<T>
provides the propertyIsDefault
which returns true if the underlying array is anull
reference. For example you can use that information to implement lazy initialization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With