#31 – Value Types and Reference Types
July 18, 2010 7 Comments
All types in C#, whether built-in or user-defined custom types, can be categorized as either value types or reference types.
- Value types
- Derive from System.ValueType (which derives from System.Object)
- Allocated on the stack (unless declared inside a reference type)
- Value type variable contains value directly
- Assignment makes a copy of the value
- Passed by value (a copy is made)
- Not garbage collected–die when they go out of scope
- Either struct or enum
- Sealed–can’t inherit from them
- Reference types
- Derive from System.Object or another reference type
- Allocated on the heap
- Reference type variable contains a reference (pointer) to the object’s contents (or contains null)
- Assignment creates a new reference to the original object
- Passed by reference (pointer to object is passed)
- Garbage collected
- One of: class, delegate, array or interface
- Support inheritance
Pingback: #185 – The Heap and the Stack « 2,000 Things You Should Know About C#
Pingback: #327 – Assigning a struct to a New Variable Makes a Copy « 2,000 Things You Should Know About C#
Pingback: #767 – A struct Is Implicitly Sealed « 2,000 Things You Should Know About C#
Pingback: #925 – The Managed Heap | 2,000 Things You Should Know About C#
Pingback: #928 – How Objects Are Removed from the Managed Heap | 2,000 Things You Should Know About C#
Pingback: #950 – C# Has a Unified Type System | 2,000 Things You Should Know About C#
Pingback: #1,032 – Requiring Generic Type Parameters to Be a Reference or Value Type | 2,000 Things You Should Know About C#