HABJAN HABJAN - 9 days ago 7
C# Question

Order of evaluation when using conditional operator

Is the following behavior expected?

public class TestClass
{
public int IntValue { get; set; }
}

TestClass instance = null;

// this line throws exception: Object reference not set to an instance of an object
string test1 = "abc" + instance != null ? instance.IntValue.ToString() : "0";

// this works
string test2 = instance != null ? instance.IntValue.ToString() : "0";

// this works
string test3 = "abc" + (instance != null ? instance.IntValue.ToString() : "0");


UPDATE:

How come this doesn't throw an exception?

TestClass instance = null;
string test4 = "abc" + instance;
string test5 = "abc" + true;

Answer

Your problem is operator preference. + ranks higher than != and ?:. Your line that is not working could be also written like this:

string test1 = ("abc" + instance) != null ? instance.IntValue.ToString() : "0";

The expression "abc" + instance is never null, even if instance is null. That means your expression always evaluates to true, which makes you run into a NullReferenceException in the instance.IntValue.ToString() expression in the case instance is null.

You can override operator precedence with parenthisation. That means you would have to make sure instance != null ? instance.IntValue.ToString() is evaluated first, by enclosing it in parentheses:

string test1 = "abc" + (instance != null ? instance.IntValue.ToString() : "0");