#31 – Value Types and Reference Types

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
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

7 Responses to #31 – Value Types and Reference Types

  1. Pingback: #185 – The Heap and the Stack « 2,000 Things You Should Know About C#

  2. Pingback: #327 – Assigning a struct to a New Variable Makes a Copy « 2,000 Things You Should Know About C#

  3. Pingback: #767 – A struct Is Implicitly Sealed « 2,000 Things You Should Know About C#

  4. Pingback: #925 – The Managed Heap | 2,000 Things You Should Know About C#

  5. Pingback: #928 – How Objects Are Removed from the Managed Heap | 2,000 Things You Should Know About C#

  6. Pingback: #950 – C# Has a Unified Type System | 2,000 Things You Should Know About C#

  7. Pingback: #1,032 – Requiring Generic Type Parameters to Be a Reference or Value Type | 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: