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.