Null in String.Format args throws NullReferenceException even arg not in result string

I have null in one of the arguments in String.Format() , so NullReferenceException throws a NullReferenceException . Why is the check being performed, even the argument is not in the resulting string?

 class Foo { public Exception Ex { get; set; } } class Program { public static void Main(string[] args) { var f1 = new Foo() { Ex = new Exception("Whatever") }; var f2 = new Foo(); var error1 = String.Format((f1.Ex == null) ? "Eror" : "Error: {0}", f1.Ex.Message); // works var error2 = String.Format((f2.Ex == null) ? "Eror" : "Error: {0}", f2.Ex.Message); // NullReferenceException } } 

Are there any workarounds other than two calls separated by if() ?

+4
source share
2 answers

This is because you end up evaluating f2.Ex.Message anyway.

Must be:

 var error2 = (f2.Ex == null) ? "Eror" : String.Format("Error: {0}", f2.Ex.Message); 
+8
source

A string.Format exception is possible, but it is: f2.Ex.Message . You call the Message getter property in Ex , which is null.

+6
source

Source: https://habr.com/ru/post/1301674/


All Articles