Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null in String.Format args throws NullReferenceException even arg isn't in resultative string

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

like image 386
abatishchev Avatar asked Dec 10 '22 17:12

abatishchev


1 Answers

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);
like image 172
Paolo Avatar answered May 09 '23 13:05

Paolo