c sharp

What is Value Type and Reference Type in C#

C# offers a range of data types for defining variables. These data types are classified as either value types or reference types, and each has its own unique characteristics. To create efficient C# code, one must know the difference between both these data types in C#. This article covers both value type and reference type details.

Table of Contents

Introduction

C# contains two distinct data types known as value types and reference types. Whenever a value type is assigned to a new variable or passed as an argument to a method, its value is copied to a new memory location. On the other hand, when a new variable is assigned a reference type or a reference type is passed as a parameter to a method in C#, only its reference is replicated.

Value Types in C#

C# includes a data type known as “value type” that directly stores its value in memory. This category includes various data types such as int, bool, char, and float. When a value type is allocated, it is stored on the stack, which is a specific area of memory designated for temporary data storage.

In C#, when a value type is assigned to a new variable or passed as a parameter to a method, the value of the variable is duplicated in a new memory location. This copy operation ensures that any alterations made to the new variable do not affect the original variable, since the two variables are stored in different memory locations.

C# Pass Value Type by Value

In C#, when a value type variable is passed from one method to another, a separate copy of the variable is created in the second method. Modifications made to the variable in the second method will not have any impact on the initial variable in the first method, in C#.

To better understand this concept, let’s examine an example where we create two variables, num1, and num2, within the Main() method. We then pass these variables to the Square() method, where we perform some operations on them. However, these operations do not affect the original variables.

using System;
namespace Example
{
    class myClass
    {
        static void Square(int a, int b)
        {
            a = a * a;
            b = b * b;
            Console.WriteLine(a + " " + b);
        }
        static void Main(string[] args)
        {
            int num1 = 5;
            int num2 = 10;  
            Console.WriteLine(num1 + " " + num2);
            Square(num1, num2);
            Console.WriteLine(num1 + " " + num2);
            Console.WriteLine("Press Enter Key to Exit..");
            Console.ReadLine();
        }
    }
}

Upon executing the above program, the resulting output is as follows:

As you can see, the changes made to the variables in the Square() method did not affect the variables in the Main() method.

The reason behind this behavior is that value types are passed by value in C#. Thus, when a variable is passed to a method, a duplicate of the variable is created, and any modifications made to the duplicate will not alter the original variable.

Reference Types in C#

C# reference types hold a reference to the memory address where the value is stored. The class, object, and string are some instances of reference types. The reference types are stored on the heap, which is an area of memory used for dynamic memory allocation.

When a reference type is assigned to a new variable or passed as a parameter to a method in C#, only the reference to the memory location where the value is stored is duplicated, not the value itself. This implies that any alterations made to the new variable will also modify the original variable.

Passing Reference Type by Value in C#

When a reference type variable is passed from one method to another in C#, a separate copy of the variable is not created. Instead, the memory address of the variable is passed, so any modifications made to the variable in one method will be reflected in another method as well.

To better understand the concept of passing reference types by value, let’s consider an example.

using System;
namespace cSharpExamples
{
    class Person
    {
       public int age;
    }
    class Program
    {
         static void Square(Person a, Person b)
         {
               a.age = a.age * a.age;
               b.age = b.age * b.age;
               Console.WriteLine(a.age + " " + b.age);
         }
         static void Main(string[] args)
         {
               Person p1 = new Person();
               Person p2 = new Person();
               p1.age = 5;
               p2.age = 10;
               Console.WriteLine(p1.age + " " + p2.age);
               Square(p1, p2);
               Console.WriteLine(p1.age + " " + p2.age);
               Console.WriteLine("Press Any Key to Exit..");
               Console.ReadLine();
         }
    }
}

Here in the above code, we define a new class named “Person” and instantiate an object of this class within the Main() method. We assign values to the variables of this instance, and we pass this instance to the Square() method. Changes are made to the variables of the “person” instance in the “Square()” method, and these modifications are reflected in the “Main()” method.

When we run the above program, we get the following result:

As you can see from the output, the changes made to the variables in the Square() method are also reflected in the Main() method.

So, this is how we can use reference type by value in C# programming language based on our requirements.

Differences between Value Types and Reference Types

The fundamental contrasts between value types and reference types can be summarized as follows:

  • Value types hold their values directly in memory, whereas reference types store a reference to the memory location.
  • The variable value is copied to a new location when the value type is assigned or given to a new variable or if it is passed as a parameter to a method. However, when a reference type is passed or assigned, only the reference to the memory location is copied.
  • Value types in C# are stored on the stack while on the other hand, the reference types are allocated heap.
  • In contrast to reference types, which have a variable size, value types have a fixed size.

Conclusion

Value types and reference types are the two distinct data types in C#. Value types are best suited for simple data types that do not require complex operations, while reference types are best suited for complex data types that require dynamic memory allocation and complex operations. Read more on both data types in this article.

About the author

Kashif

I am an Electrical Engineer. I love to write about electronics. I am passionate about writing and sharing new ideas related to emerging technologies in the field of electronics.