Search code examples
c#nullreferenceexceptionnull-coalescing-operator

Why does the Null Coalesce Operator still return null?


I have this routine:

    try
    {
        CurrentSessionName = SelectedSession?.Name ?? "No Session Selected";
        CurrentSessionTolerance = SelectedSession?.Tolerance.ToString() ?? "N/A";
        CurrentSessionVerification = SelectedSession?.Verification.Description ?? "N/A";
    }
    catch (Exception ex)
    {
        var whatever = ex.GetType(); // hits here with no provided information
        Console.WriteLine("Null Reference Exception"); // ignores this
        string name = SelectedSession?.Name; // and this
    }

So why does it still throw a NullReferenceException error even if SelectedSession is not Null?


Solution

  • Tolerance or Verification could be null and you are calling ToString() function on a null pointer.

    You can't call ToString() on a null pointer.