C# - Value Types Versus Reference Types

C# - Value Types Versus Reference Types

C# types can be divided mainly into two categories: value types and reference types. In this article, we would be having a closer look at these two types.

Value Types

  • Most of the c# built-in types such as numeric types, char types and boolean types are value types.

  • custom structs and enum types are also value types.

  • content of a value-type variable or constant is simply a value.

  • The assignment operator always copies the value.

      int a = 10;
      int b = 7;
      b = a;   // copies the value of a into b
      Console.WriteLine(" a = {0}, b = {1}", a, b);  //  a = 10, b = 10
      a = 15;  // b won't change
      Console.WriteLine(" a = {0}, b = {1}", a, b);  //  a = 15, b = 10
    

custom value types

custom value types can be created using struct or enum .

 public struct Point { public int X; public int Y; }
 Point p1 = new Point();
 p1.X = 7;
 Point p2 = p1; // Assignment causes copy
 Console.WriteLine (p1.X); // 7
 Console.WriteLine (p2.X); // 7

 p1.X = 9; // Change p1.X
 Console.WriteLine (p1.X); // 9
 Console.WriteLine (p2.X); // 7

Reference Types

  • A reference type has two parts: an object and the reference to that object.

  • content of a reference-type variable or constant is a reference to an object that contains the value.

  • a class type, an interface type, an array type, a delegate type, or the dynamic type are all reference types.

public class Point { public int X, Y; }
Point p1 = new Point();
p1.X = 7;
Point p2 = p1; // Copies p1 reference
Console.WriteLine (p1.X); // 7
Console.WriteLine (p2.X); // 7
p1.X = 9; // Change p1.X
Console.WriteLine (p1.X); // 9
Console.WriteLine (p2.X); // 9

value types and reference types and null

  • null can be assigned to reference types without any issue. assigning null to a reference type indicates that the reference points at nothing.

  • a value type cannot have null [Except Nullable Value types ]

    int x = null // compile time error

💡
The fundamental difference between value types and reference types is how they are handled in memory. Value types occupy the memory required to store the field for example 4 bytes for an integer field. However, since the reference type has two parts, it requires separate allocations for reference and object.

That's it for this article. Thanks for reading it. Please share your thoughts into comment section.

Did you find this article valuable?

Support Deepak Kumar Jain by becoming a sponsor. Any amount is appreciated!