Search code examples
c#null-conditional-operator

Null conditional and ToString together give unexpected results


I have 2 statements that use the null conditional (?) operator and perform ToString on the result. These 2 statement seem like they should have the same result, but they do not. The only different is one includes parenthesis and the other does not.

using System.Diagnostics;
using System.Net;

namespace ByPermutationConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            SomeClass someClass = default(SomeClass);

            // Why do these evaluate differently?
            //
            // (someClass?.StatusCode).ToString() is equal to an empty string
            //
            // someClass?.StatusCode.ToString() is equal to null
            //
        }
    }

    public class SomeClass
    {
        public HttpStatusCode StatusCode { get; set; }
    }
}

I expect these 2 statements to evaluate identically.

(someClass?.StatusCode).ToString() == someClass?.StatusCode.ToString()

However, they do not:

(someClass?.StatusCode).ToString() is equal to string.Empty

and someClass?.StatusCode.ToString() is equal to null


Solution

  • someClass?.StatusCode evaluates to Nullable<HttpStatusCode>. ToString on an empty Nullable results in empty string.

    someClass?.StatusCode.ToString() short circuits the whole expression to null.

    By using the parens, you are effectively breaking up the whole expression.