Why does the C# Programming Guide on "Using Nullable Types" list a nullified array as an example?

StackOverflow https://stackoverflow.com/questions/21344629

  •  02-10-2022
  •  | 
  •  

As I understand it, in C#, arrays are reference types. So they can be null. It would be silly to bother with System.Nullable<T> or the '?' operator when you're dealing with arrays, right?

Wrong - or at least it seems that Microsoft's official C# Programming Guide thinks so. On the page Using Nullable Types, they list this as an example:

int?[] arr = new int?[10];

Why would they bother to make an array a nullable type? Isn't it already nullable, by default?

有帮助吗?

解决方案

It's not the array itself that's nullable, it's the value of each entry.

This is a reference to an array of nullable integers:

int?[] arr

This is a reference to an array of integers:

int[] arr

其他提示

It is not the array which is made in the above example nullable by using the '?' . It is the int that is made nullable, so this is an array of nullable ints. And as you probably know integers are not nullable by default because they are value-types not reference-types.

No, there is obvious difference.You can't assign null value to an element of int array, consider this:

int[] numbers = new int[5];
numbers = null; // error

But you can assign a null value if you define an array of nullable types:

int?[] arr = new int?[10];
arr[0] = null; // ok
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top