I have a parameter defined like that: params object?[] values
and I cannot send null in (i.e. I would like to have an array with one null inside).
It does work without params.
The error is: Cannot convert null literal to non-nullable reference type.
public class Foo
{
private void DoesNotWork(params object?[] values)
{
}
private void DoesWork1(object? value)
{
}
private void DoesWork2(object?[] values)
{
}
public void Test()
{
DoesNotWork(null);
DoesWork1(null);
DoesWork2(new object?[] { null });
}
}
Am I doing something wrong or is there is some limitation in compiler that does not allow this?
P.S. It does as well work if the method "DoesNotWork" is from the library that does not have nullable turned on, i.e. it is defined like this: DoesNotWork(params object[] values)
, so I can send null there.
P.P.S. I have found that this workaround works as well:
DoesNotWork((object?) null);
.
P.P.P.S. DoesNotWork(null!);
works as well
you are getting the error since the single parameter provided is null, the compiler will send down null instead of creating an array with provided params:
DoesNotWork(null); // creates no array
DoesNotWork((object?)null); // creates array with one null element
DoesNotWork(null, null); // create array with two null elements
if you were to change the signature of the method to:
void DoesNotWork(params object?[]? values)
then you will not get the warning, or you suppress the warning with !
as you did