Pages

Men

rh

6/16/2012

Difference between Value Types and Reference Type in C#

Value Types:
  • Value types are stored in Stack.
  • Value types cannot be inherited from Interface.
  • No finalize to clean the resources.
  • Value type contains actual value.
ü  Examples
             Structures. Enum

Reference Types:
  • Reference Types are stored in Queue.
  • Reference type can be inherited from Interface as well as Interface.
  • Garbage Collector will clean the resources.
  • Reference types contain address of the variable.
ü   Example:   
                    Class, Delegates, Array, Interface


Example of Value Type:
 
Class PassingValue
{
            Public void  Multiply(int x)
            {
                X *=x;
                Console.WriteLine(“The Value is…. “, x);
            }
            Public Static void Main()
            {
                        Int  myint = 5;
                        Console.WriteLine(“The Value is…” myint);
                        Multiply(myint);
                        Console.WriteLine(“The Value is….”, myint);
            }
}
Output :
            The Value is…. 5
            The value is….25
            The value is….5


Passing Value by Reference:

Class PassingValueByReference
{
            Public void Multiply (ref int x)
            {
                X *=x;
                Console.WriteLine (“The Value is…. “, x);
            }
            Public Static void Main ()
            {
                        Int  myint = 5;
                        Console.WriteLine(“The Value is…” myint);
                        Multiply(ref myint);
                        Console.WriteLine(“The Value is….”, myint);
            }
}

Output :
            The Value is…. 5
            The value is….25
            The value is….25


No comments :

Post a Comment