Home > front end >  How to avoid null params with nullable reference types
How to avoid null params with nullable reference types

Time:11-18

Since C# 8.0 nullable reference types are possible. If they are enabled you have to append the ? to the reference type to make it nullable.

My question now is how can I force a method parameter that uses the params keyword, to be not-nullable.

Example:

#nullable enable
public void MyMethod(params int[] foo)
{
    // foo can still be null
    // How can I ensure that foo is not null at compile-time
}

MyMethod(null); // valid, but why?

Another question which is similar, would be: Why is params int[] foo even nullable in the first place? I would expect something like params int[]? foo to make it nullable. But with params this seems to be different.

I tried NotNullAttribute but this only gives a warning. I want to disallow that completely by the compiler.

Does anybody know a way to make it non-nullable and maybe can tell me why params allows nullable even with #nullable enable?

CodePudding user response:

this will be valid too

MyMethod();

it has nothing to do with nullables. You use nullable a wrong way here. It is because you are using the params keyword.

From MSDN

"Using the params keyword, you can specify a method parameter that takes a variable number of arguments. The parameter type must be a single-dimensional array.

When you call a method with a params parameter, you can pass in:

....

No arguments. If you send no arguments, the length of the params list is zero. "

When you pass null, you are assigning null to arguments explicitly.

but if you want to use nullable and compiler wornings, make your code like this

#nullable enable
public void MyAnotherMethod()
{

MyMethod(null); // Compiller will issue a warning

MyMethod(); // No warning
}

CodePudding user response:

  • valid, but why?

Parameter arrays where introduced before the nullable reference types and from the documentation it is valid to pass null as a value for such parameter:

A caller can then invoke the method in either of four ways:

  • By passing an array of the appropriate type that contains the desired number of elements.
  • By passing a comma-separated list of individual arguments of the appropriate type to the method.
  • By passing null.
  • By not providing an argument to the parameter array.
  • Does anybody know a way to make it non-nullable and maybe can tell me why params allows nullable even with #nullable enable?

If the call is made inside nullable enabled context compiler should issue a warning. You can change this warning into by changing compiler settings. See this question.

  • Related