1

Nullable<T> is a ValueType so you are guaranteed to never have a null reference on a Nullable<T>, but the following passes;

    [Test]
    public void ShouldTestNullRef()
    {
        int? value = null;
        IsNull(value).Should().BeTrue(); // Passes
        IsNull(new Nullable<int>()).Should().BeTrue(); // passes
    }

    private bool IsNull<T>(T nullable)
    {
        return nullable == null;
    }

Shouldn't IsNull always return false for Nullable<T>?

Is this fancy compiler magic?

References to Nullable: (https://msdn.microsoft.com/en-us/library/b3h38hb0%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396)

Edit: This is different than Which is preferred: Nullable<>.HasValue or Nullable<> != null?

When I run IsNull for ReferenceTypes It returns as expected, but when I decompile I don't see two versions of the method. My question is about the implementation potentially of how perhaps Generics are working with differences to (nullable) structs. For instance IsNull doesn't know that nullable is a struct or a value type.

leat
  • 1,418
  • 1
  • 15
  • 21
  • "Nullable is a ValueType so you are guaranteed to never have a null reference" uh? it is Nullable which means it CAN be null isn't it – Steve Oct 24 '16 at 19:33
  • https://referencesource.microsoft.com/#mscorlib/system/nullable.cs,83 – DaveShaw Oct 24 '16 at 19:33
  • 1
    @Steve No, the OP is correct. `Nullable` is a value type, so it will never *be* a null reference. A null reference is, however, implicitly convertible to any nullable type, so you can compare it to null and have it return `true` without it actually being `null`. – Servy Oct 24 '16 at 19:34
  • 1
    `Nullable.Equals(object)` is overridden. `bool? b = null; if (b == null) { /* put a breakpoint here */ }` – 15ee8f99-57ff-4f92-890c-b56153 Oct 24 '16 at 19:34
  • http://stackoverflow.com/questions/25629207/nullablet-implementation or http://stackoverflow.com/questions/2503811/how-are-nullable-types-implemented-under-the-hood-in-net – rholek Oct 24 '16 at 19:35
  • @EdPlunkett Can you make that an answer? – leat Oct 24 '16 at 19:37
  • @leat No, because the question is closed, and also I just read that the compiler replaces the comparison to a call to `HasValue`. I'd have to research that before I stuck my neck out. – 15ee8f99-57ff-4f92-890c-b56153 Oct 24 '16 at 19:38
  • 1
    If you decompile `IsNull` method, then you should see, that null comparison implemented as `box(nullable) == null`. Now you need to read about special rules for boxing `Nullable<>` type. – user4003407 Oct 24 '16 at 19:44
  • @leat See? I came up with something that seemed plausible but I was full of crap. Let this be a lesson to you. – 15ee8f99-57ff-4f92-890c-b56153 Oct 24 '16 at 19:51
  • @Servy I changed / updated the question can you un-mark as duplicate? – leat Oct 24 '16 at 22:38

0 Answers0