Thursday, June 14, 2007

"value type" and "reference type" in .Net + Concept + Example

Value Type and Reference Type Concept in .Net

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

1) As name suggest Value Type stores “value” directly.
2) 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.
3) For each instance of value type separate memory is allocated.
4) Stored in a Stack.
5) It Provides Quick Access, because of value located on stack.



Reference Type

1) As name suggest Reference Type stores “reference” to the value.
2) 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;
3) Reference type are stored on Heap.
4) It provides comparatively slower access, as value located on heap.


Note:
The behavior of strings is different, strings are immutable (unchangeable) if we alter a strings value, we create an entirely new string), so strings don’t display the typical reference-type behavior. Any changes made to a string within a method call won’t affect the original string.

1 comment:

Unknown said...

Any one could please provide more details on String reference behavior ?

Most Recent Post

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape