How does string.Format handle null values?

后端 未结 3 799
野性不改
野性不改 2021-02-11 11:45

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

3条回答
  •  花落未央
    2021-02-11 12:40

    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");
    

提交回复
热议问题