CSharp - Comparison between Value Types and Reference Types

Introduction

Examples of value types are common built-in data types (e.g., int, double, char, bool, etc.), enum types, and user-defined structures.

String is a built-in data type but also a reference type.

Examples of reference types are class (objects), interface, arrays, and delegates.

Built-in reference types include object, dynamic, and string.

The fundamental difference between the two types is the way they are handled inside memory.

Assignment of a value type always causes a copy of the instance.

Assignment of a reference type causes it to copy the reference only, not the actual object.

In general, a value type does not have a null value.

A reference type can point to null (i.e., it is not pointing to any object).

The following code shows the difference between Value Types vs. Reference Types during assignment.

Demo

using System;

struct MyStruct
{
    public int i;
}
class MyClass//from   w  ww  .  j  a v  a2s. c  o m
{
    public int i;
}
class Program
{
    static void Main(string[] args)
    {
        MyStruct struct1, struct2;
        struct1 = new MyStruct();
        struct1.i = 1;
        struct2 = struct1;

        MyClass class1, class2;
        class1 = new MyClass();
        class1.i = 2;
        class2 = class1;

        Console.WriteLine("struct1.i={0}", struct1.i);//1
        Console.WriteLine("struct2.i={0}", struct2.i);//1
        Console.WriteLine("class1.i={0}", class1.i);//2
        Console.WriteLine("class2.i={0}", class2.i);//2

        Console.WriteLine("***Making changes to strcut1.i(10) and class1.i(20) * **");

        struct1.i = 10;
        class1.i = 20;
        Console.WriteLine("struct1.i={0}", struct1.i);//10
        Console.WriteLine("struct2.i={0}", struct2.i);//1
        Console.WriteLine("class1.i={0}", class1.i);//20
        Console.WriteLine("class2.i={0}", class2.i);//20
    }
}

Result

Analysis

We can see that both class objects-class1 and class2-have updated their instance variable i when we made the change in class1.

But the same did not happen for structures.

struct2.i is keeping the old value 1, even if struct1.i changed to 10.

When we wrote struct2 = struct1;

The struct2 structure becomes an independent copy of struct1, with its own separate fields.

When we wrote class2 = class1;

We are copying the reference, which is pointing to the same object.

Related Topic