Saturday, 28 February 2009

C# Variable : Value type and Reference Type

In any programming language , Variables hold a very important place. While working with variables , we should keep in mind




  1. Variables are declared as being of particular type.

  2. Each variable is constrained to hold only valuesof its declared type

In C# , there are two types of variable : Value Type and Reference Type


Value Type:


All value types are derived implicitly from the System.ValueType. It includes all predefined datatypes , Structs and Enumerators.


In the following code , two variables are declared and set with the integer values.


int x = 1;


int y = x;


y=2;


after this statement , x holds the value 1 and y holds the value 2.

Reference Type:

The predefined reference types are objects and string. User defined types are:

  • Class
  • Interface
  • Delegate

Reference types actually hold the value of a memory address occupied by the object they reference .Consider the following piece of code , in which two variables are given a reference to the same object.

Object x = new Object();

x.newValue = 1

Object y = x

y.newValue = 2

After this statement both x.newValue and y.newValue equal to 2.

Strings , though they are reference type , they work more like value types.

String s1 = "Hello";

String s2 = s1;

s2 = "Bye";

After this statement s1 holds "Hello" and s2 holds "Bye".

Its because immutable property of the String and when the value of the s1 change , a new string object is created .

One should declare a type as a value type if all the following are true

  • The type acts like a primitive type
  • The type does not need to inherit from anyother type
  • The type will not have any othe types derived from it.
  • Objects of the type are not frequently passed as method arguments since this would cause frequent memory copy operation hurting performance.



No comments:

Post a Comment