Search code examples
c#arraysnullable

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


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?


Solution

  • 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