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.
is converted into
this checks its arguments for null and only converts them to strings if they are not. This means that
is
false
so the expressionis evaluated. This throws an exception since
ex.InnerException
is null.