views:

199

answers:

3

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.

+10  A: 

Incorrect - value types are objects, they are just objects stored on the stack instead of the heap. 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.

thecoop
Thank you. I most likely misread the information (and may have been misinformed).
Norla
Value types *are not* "just objects stored on the stack instead of the heap". Maybe they're *usually* stored on the stack, but not always, and it's certainly not this that distinguishes value types from ref types.
LukeH
Yes, value types can be boxed and can be in a class (and so on the heap inside a ref class instance), but that is the easiest way to think about and to communicate how they behave.
thecoop
The point is that the behaviour of value types is completely unrelated to how/where they're stored. After all, the semantics don't change depending on whether they're stored on the stack or the heap, do they?
LukeH
A: 

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.

Lasse V. Karlsen
Nullable types are structs (according to thecoop) and cannot inherit from *anything*.
RCIX
Technically they do. Check http://stackoverflow.com/questions/1793357/do-value-types-integer-decimal-boolean-etc-inherit-from-object
Lasse V. Karlsen
Also see http://blogs.msdn.com/ericlippert/archive/2009/08/06/not-everything-derives-from-object.aspx
Lasse V. Karlsen
@RCIX: I did not say that. To quote - '...and so inherits from System.ValueType and System.Object'
thecoop
A: 

Everything is an object, value types are just structs rather classes.

Paul Creasey
Actually, pointer types _aren't_ objects - see http://blogs.msdn.com/ericlippert/archive/2009/08/06/not-everything-derives-from-object.aspx
thecoop