Difference between Value and Reference type in C#.net

Difference between Value and Reference type in C#.net

Value Type and Reference Type

A variable is value type or reference type is solely determined by its data type.

Eg: int, float, char, decimal, bool, decimal, struct, etc are value types, while object type such as class, String, Array, etc are reference type.

 

Value Type

As name suggest Value Type stores “value” directly.Memory is allocated at compile time.

For eg:

//I and J are both of type int

I = 20;

J = I;

int is a value type, which means that the above statements will results in two locations in memory.

For each instance of value type separate memory is allocated.

Stored in a Stack.

It Provides Quick Access, because of value located on stack.

 

Reference Type

As name suggest Reference Type stores “reference” to the value.Memory is allocated at run time

For eg:

Vector X, Y; //Object is defined. (No memory is allocated.)

X = new Vector(); //Memory is allocated to Object.//(new is responsible for allocating memory.)

X.value = 30; //Initialising value field in a vector class.

Y = X; //Both X and Y points to same memory location.//No memory is created for Y.

Console.writeline(Y.value); //displays 30, as both points to same memory

Y.value = 50;

Console.writeline(X.value); //displays 50.

Note: If a variable is reference it is possible to indicate that it does not refer to any object by setting its value to null;

Reference type are stored on Heap.

It provides comparatively slower access, as value located on heap.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply