C# 12 - How do I make sense of this behavior? Passing an array of non-nullable reference type to a parameter expecting nullable reference type array

6 days ago 9
ARTICLE AD BOX

I am on a quest to understand the nullable reference type system in C# (well, I guess the non-nullable reference types are the unique part). The mechanics of this particular situation are totally lost on me.

I have a method

private static void ArrayModify<E>(E?[] arr) where E : class { }

(The class constraint is just to guarantee that null can actually be assigned to an element of the array in some hypothetical code.)

If I write the following:

string[] array = new string[3]; ArrayModify(array);

I get no warnings or errors. This makes no sense to me. I understand why a non-nullable type can be implicitly converted to a nullable type normally. But being able to implicitly cast A to B doesn't mean you can implicitly cast A[] to B[]. And in this case, if I assign null to an element within the function, then I will have a null element in my array of supposedly non-nullable strings.

To further complicate things, if we change ArrayModify to expect a ref param:

private static void ArrayModify<E>(ref E?[] arr) where E : class { }

Then write:

string[] array = new string[3]; ArrayModify(ref array);

Now I get a CS8620 warning ("Argument cannot be used for parameter due to differences in the nullability of reference types") which is what I expected in the first place... but what is the difference??

Read Entire Article