RononDex
RononDex

Reputation: 4173

Why does this produce a nullable array / How to create non-nullable array

Is it possible to create non-nullable arrays in C#? If so how?

Given the following code:

var someArray = new int[10];

This makes someArray of type int[]?, meaning the array itself is nullable. However, how is it possible to declare a non-nullable array with the C# 8.0 Nullable feature enabled?

Upvotes: 2

Views: 1547

Answers (2)

Youssef13
Youssef13

Reputation: 4944

While the type is int[]?, you won't get warnings if you try to access it. The language design team decided to always treat var as nullable reference type, and rely on DFA (DataFlow Analysis) for when to produce warnings. This isn't specific to arrays. See dotnet/csharplang#3662 for detailed discussion.

Also, from var keyword docs:

When var is used with nullable reference types enabled, it always implies a nullable reference type even if the expression type isn't nullable.

Upvotes: 3

DevNull
DevNull

Reputation: 141

int[] actually derives from Array. from Microsoft "all arrays are actually objects"

All objects are nullable (for all versions of C#), thus the "nullability" of value types more recently introduced doesn't impact the array case.

Now as to the question of how to prevent an object being null. Perhaps you could be really clever with runtime modifications to prevent null assignment, but going to be terribly tricky, and still likely to have holes (unsafe assignments for one)

It is quite likely that a pivot of the larger problem will reveal a larger data-structure. In that data structure you could encapsulate the array behaviour, and rely on your own coding diligence to keep it non-null. And with the array stored as a private variable you can be assured no one else can assign null to it. Now of course the outer object could be null, but you can save yourself from the null checks in your inner code.

class Foo {
   private int[] someArray = new int[10];

   public int[] getArray { return someArray; }

   // Insert your amazing stuff here
}

Upvotes: 0

Related Questions