Difference between Value Type and Reference Type

By | September 10, 2019
Value Type
Reference Type
Data stored in stack memory Data stored in heap memory
When passed as value type new copy is created and passed so changes to variable does not get reflected back. When passed as Reference type then reference of that variable is passed so changes to variable does get reflected back.
Value types are faster in access Reference types are slower in access.
Value types derived from System.ValueType Reference types derived from System.Object
Example: int ,struct, bool etc are value types. Example: class, string, interface etc are reference types.

 

Value type:

class Program
{
    static void Main(string[] args)
    {
        int x = 5;
	Console.WriteLine("Before method call", x);
        ChangeValueType(x);
	Console.WriteLine("after method call", x);  
    }
    public void ChangeValueType(int x)
    {
        x = x + 5; Console.WriteLine("Inside method call", x);
     }
}

Output:

Before method call=5
Inside method call=10
After method call=5

We can see that when pass the value of x inside the method actually we are creating new object that’s why after the execution on method we does not get the change value because we internally changing in new x value.
This is also called Pass By Value

 

Reference type:

class Program
{
    static void Main(string[] args)
    {
      int[] x = new int[1];
      x[0] = 5;
      Console.WriteLine("Before method call", x[0]);
      RefecenceValueType(x);
      Console.WriteLine("after method call", x[0]);       
    }

     public void ChangeValueType(int x)
     {
         x = x + 5; Console.WriteLine("Inside method call", x);
      }
}

 

Output:

Before method call=5
Inside method call=10
After method call=10

We can see that when pass the value of x inside the method actually we are passing memory location of new object and when we modify the value inside the method actually we are modifying the actual value because both object have same memory location. This is also called Pass By Reference

We can see memory location of Value Type and Reference Type inside the below screenshot.

 

I hope you will enjoy the difference between Value type and Reference type in c#. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Like it? Share it