views:

142

answers:

2

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()?

+6  A: 

It is not string.Format that is throwing the exception but this: f2.Ex.Message. You are calling the Message getter on Ex property which is null.

Darin Dimitrov
+8  A: 

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);
Paolo
+1 beat me to it...
Sani Huttunen
+1 for the code example, which explains the point better than Darins answer.
Mauro