c# – String.Format with null parameter


This code:

Console.Write(string.Format("Value = {0}", (object)null));

does not throw an exception

And here:

Console.Write(string.Format("Value = {0}", null));

there will be an exception Значение не может быть неопределенным. … Why?


And these examples

Console.Write($"Value = {null}");
Console.Write($"Value = {(object)null}");

will not throw an exception


Let me remind you that passing an arbitrary number of arguments to string.Format is implemented through params object[] args . The peculiarity of this notation is that if you pass exactly one instead of a set of arguments, which can be cast to the object[] type, the compiler will convert it to this type, otherwise the compiler will create a new array.

Accordingly, when null is passed as the second argument, this null takes the type of an array of objects, hence the error. The second parameter string.Format cannot be null.

At the same time, if you write (object)null , then you won't be able to pass it as an array, and the compiler behind the scenes will do this: new object[] { (object)null } , and this option is completely correct.

Correction: the compiler will actually choose the Format(string, object) overload instead of creating an array – but that's just an optimization

This option will work in the same way: string.Format("Value = {0}", null, null) , because two arguments cannot be one array in any way.

As for the option with interpolation, it has no syntactic ambiguity, and therefore any option works.

Scroll to Top