I cannot figure out why the following program compiles without warnings, but in the exception block the conditional operator gives a NullReferenceException.
using System;
namespace Playground
{
class Program
{
static void Main(string[] args)
{
string message1 = "First message.";
string message2 = null;
// This works without a problem
Console.WriteLine(message1 + message2 == null ? "" : Environment.NewLine + message2);
Console.ReadKey();
try
{
throw new Exception("Now with an exception.");
}
catch (Exception ex)
{
// This will give a NullReferenceException:
Console.WriteLine(ex.Message + ex.InnerException == null ? "" : Environment.NewLine + ex.InnerException.Message);
// ..But this will work:
Console.WriteLine(ex.Message + (ex.InnerException == null ? "" : Environment.NewLine + ex.InnerException.Message));
}
}
}
}
I know about the ??
operator, my question is about why the first line in the exception handler gives a NullReferenceException.
ex.Message + ex.InnerException
is converted into
string.Concat(ex.Message, ex.InnerException);
this checks its arguments for null and only converts them to strings if they are not. This means that
ex.Message + ex.InnerException == null
is false
so the expression
Environment.NewLine + ex.InnerException.Message
is evaluated. This throws an exception since ex.InnerException
is null.