I have a null
in one of arguments in String.Format()
so call throws NullReferenceException
. Why does check take place even the argument isn't in resultant 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 except two calls separated by if()
?