#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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

2 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#

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 )

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

Follow

Get every new post delivered to your Inbox.

Join 43 other followers