Loading ...

Value type vs Reference type in C# | CodeAsp.Net

Value type vs Reference type in C#

 /5
0 (0votes)

 

Value types are allocated on the stack, while all reference types are allocated on the heap.  A value type contains the actual value. A reference type contains a reference to the value.

When a value type is assigned to another value type, it is copied. When a reference type is assigned to another reference type, a reference is assigned to the value.

As you can see in below example:

 

using System;
public class AgeClass
{
private int age;

public void SetAge(int years)
{
age = years;
}
public int GetAge()
{
return age;
}

}
public class DataTypeTest
{
public static void Main()
{
int i, j;
i = 23;
j = i;
Console.Write("Value Of i:{0}",i);
Console.Write("\nValue Of j:{0}",j);
i = 24;
Console.Write("\nValue Of i:{0}",i);
Console.Write("\nValue Of j:{0}", j);

AgeClass ajit = new AgeClass();
ajit.SetAge(23);

AgeClass sumit = ajit; //Sumit now equals ajit

Console.Write("\nAge Of AJIT:{0} ",ajit.GetAge());
Console.WriteLine("\nAge Of Sumit:{0} " , sumit.GetAge());
ajit.SetAge(24); //change Ajit's age, what Sumit to ajit now?
Console.Write("\nAge Of AJIT:{0} ", ajit.GetAge());
Console.WriteLine("\nAge Of Sumit:{0} ", sumit.GetAge());

Console.WriteLine(ajit == sumit);
}

}





the output of the program is:

OutPut

 

 

 

 

As we are seeing that first i copy value type(int type) variable i into another value type variable j when i chane the value of
i value of j has not changed on the other hand when i changed the value of a refernce type variable (class instance) ajit then 
the value indise anothe instance sumit haschange because it hold the copy of ajit.


All value types are implicitly derived from System.ValueType. This class actually overrides the implementation in System.Object, the base class  for all objects which is a reference type itself. 

Data types like integers, floating point numbers, character data, Boolean values, Enumerations and Structures are examples of Value Types. Classes, Strings, Arrays are examples of Reference Types. 

A value type may not contain NULL values. Reference types may contain NULL values.

 

Comments (no comments yet)

Top Posts