Search code examples
c#nullable-reference-types

Nullable reference types on object array


I've a .NET 6 project with non-nullable reference types.

I want to constrain the objects parameter to a non-nullable array of nullable objects.

I've 4 possible methods and assume one of these should work.

public void Method1(object[] objects)

public void Method2(object[]? objects)

public void Method3(object?[] objects)

public void Method4(object?[]? objects)

Method2 and 4 both accept a null. So I'm left with 1 and 3 but I get a warning on both:

CS8625 Cannot convert null literal to non-nullable reference type

I would expect method3 to work without warning:

Method3(new object[] { null });

Is there any way to get this done?

My question is answered in one of the comments. I should of course have used:

 Method3(new object?[] { null });

Solution

  • This answer is just for completeness, so that the answer is not only in the comments

    The problem is not with the declaration of your method and it's parameters, but instead with the call. You are creating an array of non-nullable objects and initializing it with one null. You should instead create an array of nullable objects like this: new object?[] { null }

    To answer your confusion with the method declarations:

    The nullability operator always referes to the previous type.

    So in object[]? the nullability operator applies only to the array. This means that null and an array of non-nullable objects would fit this type.

    When you write object?[], the nullability operator applies only to object. This means that a non-nullable array of nullable objects matches this type.