Types of variables in c#

value and reference type

            The c# support two major variable types, they are “Value type and Reference type”. Int, Float, Decimal , Char , etc are the value types and Classes, , Delegates , Interfaces , Arrays , etc are the Reference types.

Now we have seen c# has two different types of variable types. These types must have some difference so lets see how this value and reference type differs.

Value type and Reference type

I hope everyone knows, when ever we initialize a variable there is a memory allocation will happens, we should know this to know about the difference of value and reference types.

Value type

  • Value type variable store data directly into the memory location.
  • If we get any copy of the data to another variable and try to change any variable data , the changed data will affect only to the variable we try to change , other variable remain the old value.
  • Value type data will be saved in Stack memory.

Reference type

  • Reference type variable does not save data directly to the memory location. it stores the reference of the actual data.
  • If we get any copy of the data to another variable and try to change any variable data , the changed data affect every copy of the object.
  • Reference type data will be saved in Heap memory

Example

using System;

class RefClass
{
    public int Value = 0;
}

class TestProgram
{

static void Main() {

    int valtype1 = 0;
    int valtype2 = valtype1;
    valtype2 = 999;
    RefClass refObj1 = new RefClass();
    RefClass refObj2 = refObj1;
    refObj2.Value = 999;
    Console.WriteLine("Value type values: {0}, {1}", valtype1, valtype2);
    Console.WriteLine("Reference type values: {0}, {1}", refObj1.Value, refObj2.Value);
}

}

 

Output

Values: 0, 999
Refs: 999, 999

Value type

check the above example valtype2 is assigned from the variable valtype1 and changing the data valtype2. but in the output the change has been reflected only to the changed variable.

Reference type

check the above example refObj2 is assigned from the object refObj1 and changing the data inside the object refObj2. The change we made was in refObj2 but in the out put the change applied in the refObj2 reflected refObj1.

Leave a Reply