1) Implicitly Typed Local Variables
Local variable can be declared as var instead of explicit type.The compiler automatically takes the necessary type.This example shows this.
private void Bind()
{
DataClassesDataContext db = new DataClassesDataContext();
var sString = "anishmarokey";
var query = from n in db.tblNames
select n;
}
Result for var query;
By using ILDASM ,See the result for var sString and var query
2) Object and Collection Initializers
With out invoking the constructor ,values can be accessible to fileds or properties
in .NET 2.0 invoking constructor value
using System;
class objectInitializers
{
public int Age { get; set; }
public string Name { get; set; }
}
class Application
{
static void Main()
{
objectInitializers o = new objectInitializers();
o.Age = 24;
o.Name = "anishmarokey";
}
}
The compiler takes it as
In .NET 3.5 without invoking constructor
using System;
class objectInitializers
{
public int Age { get; set; }
public string Name { get; set; }
}
class Application
{
static void Main()
{
objectInitializers obj = new objectInitializers { Age = 24, Name = "anishmarokey" };
}
}
The compiler takes it as
Note : Code size is different,for .NET 3.5 Code size is little higher.All the other things are same
When we want to initialize a collection class that class should initialize IEnumerable.
in .NET 2.0
static void Main()
{
List<string> l = new List<string>();
l.Add("A");
l.Add("B");
l.Add("C");
}
The compiler takes it as
in .NET 3.5
static void Main()
{
List<string> l = new List<string> { "A", "B", "C" };
}
The compiler takes it as
Note : Code size is different,for .NET 3.5 Code size is little higher.All the other things are same
3) Extension Method
As per ScottGU - Extension methods allow developers to add new methods to the public contract of an existing CLR type, without having to sub-class it or recompile the original type.
using System;
public static class NewFeature
{
public static int TointNewFeature(this int i, int j)
{
return i + j;
}
public static int TointOldFeature(int i, int j)
{
return i + j;
}
}
class App
{
static void Main()
{
int iDemo = 2.TointNewFeature(3);
Console.WriteLine(iDemo);
iDemo = NewFeature.TointOldFeature(2, 3);
Console.WriteLine(iDemo);
}
}
4) Anonymous Type
A convenient way to encapsulate a set of read only properties into a single object without having to first explicitly define type.
DataClassesDataContext db = new DataClassesDataContext();
var query = from n in db.tblNames
select new { n.name };
5)
Lambda Expression( => )It can be used to create a delegate or a expression type
Example taken from
MSDNdelegate int del(int i);
static void Main(string[] args)
{
del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25
}
6) Auto Implemented Properties
If we declare this the compiler automatically adds the get accessor method and set accessor method to the corresponding properties.
in .NET 3.5
class Test
{
public int Age { get; set; }
}
The compiler takes it as