How does string.Format handle null values?

后端 未结 4 1360
感情败类
感情败类 2021-02-11 12:07

In the following code below, why do the two string.Format calls not behave the same way? In the first one, no exception is thrown, but in the second one an Ar

4条回答
  •  旧时难觅i
    2021-02-11 12:35

    In case you use an interpolated string ($"", another way to format), the null is ignored, skipped. So

    string nullString = null;
    Console.WriteLine($"This is a '{nullString}' in a string");
    

    will produce: "This is a '' in a string". Of course you can use the null coalescing operator in case of null to produce the output needed:

    string nullString = null;
    Console.WriteLine($"This is a '{nullString ?? "nothing"}' in a string");
    

提交回复
热议问题