2

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?

4
  • correct me if i'm wrong, but isn't the whole point of the c# 8 nullable feature that everything is nullable? Commented Feb 7, 2021 at 15:07
  • it should be non nullable by default and only nullable if you declare it using a ?. Like int? is nullable, but int isn't. The same way I would expect int[] to be non-nullable and int[]?to be nullable. Commented Feb 7, 2021 at 15:11
  • 1
    @RononDex, 'new int[10]' is non nullable and 'new int?[10]' is nullable. Commented Feb 7, 2021 at 15:34
  • 1
    @NCCSBIM071 int?[] is different than int[]?. I believe the question is about nullable referece types. Not nullable value types. Commented Feb 7, 2021 at 15:54

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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
}

1 Comment

This question is about nullable reference types.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.