In this short tutorial, you will learn C# value types and reference types.
Concept
- A value type stores its value directly, whereas a reference type stores a reference to the value; they are stored in different memory space.
- Values types are store in memory location:
Stack
. - Reference type are stored in memory location:
managed Heap
.
Value Types
Value types derive from System.ValueType
, which derives from System.Object
. Types that derive from System.ValueType
have special behavior in the CLR
.
Value type variables directly contain their values, which means that the memory is allocated inline in whatever context the variable is declared. There’s no separate heap allocation or garbage collection overhead for value-type variables.
There are two categories of value types: struct
and enum
. The built-in numeric types are structs. And you can use the struct
keyword to create your own custom value types.
Value types are sealed
, which means that you can’t derive a type from any value type.
Reference Types
A type that is defined as a class
, record
, delegate
, array
, or interface
is a reference type.
At run time, when you declare a variable of a reference type, the variable contains the value null
until you explicitly create an object by using the new
operator, or assign it an object that has been created elsewhere by using new
. When the object is created, the memory is allocated on the managed heap
, and the variable holds only a reference to the location of the object.
All arrays
are reference types, even if their elements are value types. Arrays implicitly derive from the System.Array
class.
Code Sample
Following code are using top-level statements (need >= C# 9) for simple show case:
using System; int v1 = 2; int v2 = v1; Console.WriteLine($"v1: {v1}; v2: {v2}"); v1 = 3; Console.WriteLine($"v1: {v1}; v2: {v2}"); MyPoint point1 = new MyPoint() { X = 20 }; MyPoint point2 = point1; Console.WriteLine($"point1 X: {point1.X}; point2 X: {point2.X}"); point1.X = 30; Console.WriteLine($"point1 X: {point1.X}; point2 X: {point2.X}"); class MyPoint { public int X { get; set; } }
Output:
v1: 2; v2: 2
v1: 3; v2: 2
point1 X: 20; point2 X: 20
point1 X: 30; point2 X: 30
Built-in Types
C# provides a standard set of built-in types to represent integers, floating point values, Boolean expressions, text characters, decimal values, and other types of data. There are also built-in string
and object
types. These types are available for you to use in any C# program. See built-in types here.