2

Whenever I call PropertyInfo.GetValue on a Nullable property, I obtain the nullable struct's actual value, not the struct itself. Why is it? Is it baked into the language and only available to the Nullable type or custom classes can have the same thing with other types.

1 Answers1

5

It's because PropertyInfo.GetValue's return type is object, which means that all value types are boxed.

Now, nullable types are boxed differently than other types:

  • a nullable value with HasValue == false will be boxed to the null reference, and
  • a nullable value with HasValue == true will be boxed like the underlying non-nullable type. The nullability information is "lost".

Is it baked into the language and only available to the Nullable type [...]

Exactly, (only) the Nullable struct gets special treatment by the CLR.

The reason for this special treatment is explained in detail in the following question. Basically, it boils down to wanting myNullable == null and myBoxedNullable == null to behave consistently:

Heinzi
  • 167,459
  • 57
  • 363
  • 519