Question

If value types are objects (I've seen that ValueType does indeed inherit from Object) why do they not behave as Objects? They can't be null, so it would seem they don't have a reference, and they must be boxed/unboxed. When passed as params they behave like primitives, but since you can call methods on them, they seem to behave as reference types also. I read that they are normally allocated on the stack, which makes them seem like value types again. And as far as boxing goes, I don't see Java equivalents of int and Integer, just the Int32 struct, so if an Int32 is boxed, what is it boxed into?

In short, if someone could address how they seem to stand half in one world an half in another I would certainly appreciate it.

Was it helpful?

Solution

.NET allows you to treat value types as objects because it's beneficial to have a uniform interface with which to manipulate information (read up on the uniform access principle in Eiffel, which influenced the design of C#). 5.ToString() makes more sense than Int32.ToString(5), because it's consistent with the OOP paradigm, even if it is just syntactic sugar.

Value type variables in C# 2.0 and greater can be declared nullable with the following syntax:

int? myInt;

More details about how value types work is available at http://msdn.microsoft.com/en-us/library/system.valuetype%28v=VS.85%29.aspx:

In cases where it is necessary for a value type to behave like an object, a wrapper that makes the value type look like a reference object is allocated on the heap, and the value type's value is copied into it. The wrapper is marked so the system knows that it contains a value type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top