Sunday, September 4, 2011

New Features of C# 3.0

The changes made in C# 3.0 are as follows:
  1. Local Variable Type Inference or Implicitly Typed Local Variables.
  2. Object Initializers 
  3.       Collection Initializers
  4.       Anonymous types
  5.       Auto-implemented properties
  6. Extension methods
  7. Lambda expressions
  8.        Query expressions
  9. Expression trees
  10.         Partial Methods
 Local Variable Type Inference
    var data = 1;
   data = 23.4f;                //Compile time Error
Interestingly ‘var’ can be used in any of the following ways:
Directly associating a value or type:
   var data1 = 10;             // data1 is of type System.Int32
   var data2 = 20.5f;          // data2 is of type System.Single
   var data3 = "Hello";        // data3 is of type System.String
   var data4 = new List<int>(); // data4 is of type Generic List<T>
   var data5 = new CEmployee(); // data5 is an instance of Class CEmployee
Associating with expressions:
     var data6 = 23 + 45;         // data6 is of type System.Int32
Association with methods:
In C# 2.0, if you want to call a method ( GetData( ) ) which returns you an integer, you will write something like this: 
     int data = GetData();
and if GetData() returns you a string, the above written line will throw an error, but now with ‘var’ you can write the same code as follows:
     var data = GetData();
Now even if your GetData() method returns you any type, the above written line need not be changed.
There are some rules associated with ‘var’, which are as follows:
1.    You must initialize ‘var’ type variables with some value or expression.
2.    Once the type is assigned to ‘var’ type variable you cannot change the type of value the variable holds.
3.    ‘var’ cannot be used as a return type of the methods.
var Add(int x,int y);              //Error
4.    ‘var’ cannot be used in argument list of the methods.
int Add(var x,var y);              //Error
5.    The contextual keyword 'var' can only appear within a local variable declaration         i.e. ‘var’ types can be created only inside a method or a block.