Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Are nullable types (int?) objects?

I understand from this post that value types in C# are not objects. That is, they do not inherit from System.Object.

Assuming my logic holds up to this point, are nullable types, such as int?, objects. Do they inherit from Object?

If so, are they subject to all the same rules and constraints as other objects, or are there special rules governing their behavior?

Just as reference, this question comes from an inquiry into the workings of the null coalesce operator.

like image 587
Nick Vaccaro Avatar asked Sep 14 '26 12:09

Nick Vaccaro


2 Answers

Incorrect - value types are objects, but they don't behave the same as reference types - they are pass-by-value, instead of pass-by-reference. So, Nullable<T> (which is what T? is) is a struct, and so inherits from System.ValueType and System.Object. There is Magic in the C# compiler that makes nullable types behave the same way as reference types with regards to null and ??, but they always have copy-by-value semantics.

like image 118
thecoop Avatar answered Sep 17 '26 00:09

thecoop


Are you asking about "inheriting from System.Object" or "reference types"?

Value types do inherit from System.Object, but they're not reference types.

Nullable types are also value types, so they are not reference types either, but they do inherit from System.Object.

Note that there is a difference in what you as the programmer can declare and what the system provides.

Value types do inherit from System.Object, but you cannot yourself declare value types to descend from anything.

Value types descend from System.ValueType, which in turn descends from System.Object.

So technically, all value types descend from System.Object.

like image 30
Lasse V. Karlsen Avatar answered Sep 17 '26 01:09

Lasse V. Karlsen