What are the differences between value types and reference types in C#? [duplicate]
I know a few differences,
- Value types are stored on the stack where as reference types 开发者_运维问答are stored on the managed heap.
- Value type variables directly contain their values where as reference variables holds only a reference to the location of the object that is created on the managed heap.
Is there any other difference i missed... If so,what are they?
Please read: The stack is an implementation detail, and don't ever again repeat the canard that stack allocation is what differentiates value types from reference types in .NET. The CLR may choose to allocate a variable anywhere it wants to.
The most important difference is in the assignment semantics. When you assign a value type to a variable (or pass it to a method as an argument), all of the data is copied. When you assign a reference type, only a reference is copied - both references point to the same object instance in memory.
Here are some additional differences:
- Value types cannot be inherited, whereas reference types can
- Value types are implemented as a struct, reference types as a class
- Value types, by default, cannot be assigned real null values (the ? syntax is a workaround and still doesn't result in a true null value)
- Assigning a value type to another variable, or passing it as a parameter in a method, makes a copy of it whereas with a reference type the variable represents the memory location of the object
- It is a compile-time error for a struct to declare an explicit parameterless constructor, but the same does not apply to a class
- It is a compile-time error to use the "this" object before all fields are assigned in a struct, but the same does not apply to a class
- It is a compile-time error for a struct to not fully assign all properties in its constructor, but the same does not apply to a class
As mentioned by Aaronaught and Eric blog post:
Remember the rule, Reference types always goes to the Heap, whereas Value Types always go where they were declared? If a Value Type is declared outside of a method, but inside a Reference Type it will be placed within the Reference Type on the Heap.
i think values are implicitly assigned memory but not reference types they must be assigned memory explicitly
精彩评论