-5

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?

Khalil Khalaf
  • 9,259
  • 11
  • 62
  • 104
  • 1
    Are you trying to debug in Release mode? Also `SelectedSession.Tolerance` and `SelectedSession.Verification` could be null. – Jamie Rees Jun 01 '16 at 13:07
  • well `SelectedSession` wouldn't throw, because you're using the null propogation off of it. What about `SelectedSession.Tolerance` or `SelectedSession.Verification`? – Jonesopolis Jun 01 '16 at 13:07
  • Please post your complete error + stack trace. – sstan Jun 01 '16 at 13:09
  • 2
    @FirstStep, calling `.ToString()` on null will of course throw an exception. So will accessing a property on a null object. – Jonesopolis Jun 01 '16 at 13:09
  • 1
    There is always `null` somewhere. Just need to find it. – trailmax Jun 01 '16 at 13:10
  • @FirstStep Well because it's in Release mode that's why it's jumping into the catch, and why you are seeing "Cannot evaluate expression because the code of the current method is optimized". If you are debugging, use debug mode. – Jamie Rees Jun 01 '16 at 13:13
  • I can't use `Tolerance?.ToString()` on a non string variable and the problem is in `Verification.Description` – Khalil Khalaf Jun 01 '16 at 13:32
  • 1
    Your question was interesting, but as it was all about NRE, it will always get closed as duplicate of the canonical question on that subject. I have changed your question so that it makes sense for the answer I provided - which Im 100% sure will help more people in the future. – Jamiec Jun 01 '16 at 16:28

2 Answers2

5

Null propagation operator is great - but it does not magically eliminate nulls.

This snippet

SelectedSession?.Tolerance

Will not error if SelectedSession is null, but it will propagate on so that the result of the above is null. The same applies if SelectedSession is not null, but Tolerence is null.

The problem is you then try to call ToString() on a null

SelectedSession?.Tolerance.ToString()
Jamiec
  • 133,658
  • 13
  • 134
  • 193
3

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.

Danyal Sandeelo
  • 12,196
  • 10
  • 47
  • 78