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()
?
It's because you're going to end up evaluating f2.Ex.Message
in either case.
Should be:
var error2 = (f2.Ex == null) ? "Eror" : String.Format("Error: {0}", f2.Ex.Message);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With