Managing memory with reference and value types

There are two categories of memory: stack memory and heap memory. Stack memory is fast but limited and heap memory is slow but plentiful.

There are two C# keywords that you use to create object types: class and struct. Both can have the same members. The difference between the two is how memory is allocated.

When you define a type using class, you are defining a reference type. This means that the memory for the object itself is allocated on the heap, and only the memory address of the object (and a little overhead) is stored on the stack.

When you define a type using struct, you are defining a value type. This means that the memory for the object itself is allocated on the stack.

Note

If a struct uses ...

Get C# 7 and .NET Core: Modern Cross-Platform Development - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.