1

why is the line:

Assert.IsFalse(myInt.HasValue);

possible? I would expect a NullPointerException as myInt is null.

    [TestMethod]
    public void Test_NullableInt_ShortDeclaration_WithValueAssignment()
    {
        int? myInt = null;

        Assert.IsNull(myInt);
        Assert.IsFalse(myInt.HasValue); // Why is this possible?

        myInt = 5;
        Assert.IsNotNull(myInt);
        Assert.IsTrue(myInt.HasValue);
    }

Regards

Alf Moh
  • 7,159
  • 5
  • 41
  • 50
TheAnonymousModeIT
  • 777
  • 1
  • 6
  • 18
  • This is possible because `myInt` is not actually `null`. In fact, `int?` can never be `null` at all, because it's a value type (a `struct`). C# compiler applies special tricks to make `myInt` pretend it's `null` when it has no value. – Sergey Kalinichenko Sep 10 '17 at 11:33
  • 2
    `int?` is actually `Nullable` which is a `struct` and while letting you represent empty/non-existent *values* it can't really be `null` at runtime. – haim770 Sep 10 '17 at 11:34
  • [_Nullable Types (C# Programming Guide)_](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/nullable-types/) – Ousmane D. Sep 10 '17 at 11:39

0 Answers0