C# 3.0 new language features
By : Kasim Wirama, MCDBA, MVP SQL Server
.NET 3.5 has been launched in November 2007. I read and tried new features of C# language (code name : Orcas) with Visual Studio 2008. These are new features for C# 3.0 in .NET framework 3.5 :
- Local type inference
You can declare your variable in more relaxed way, while preserving type safety on design time rather in run time.
For example you declare this variable below
int i = 5;
you can write as below :
var i = 5;
Compiler will know that variable i has type integer.
- Lambda expression
You can define anonymous method with more flexible syntax, it is other alternative to delegate use.
For example when you express in delegate :
Sum = Aggregate ( l.values, delegate( int a, int b) {return a + b;});
With lambda expression you can replace as:
Sum = Aggregate ( l.values, (int a, int b) => {return a + b;} );
It is called explicitly type parameter list.
You can simplify it further :
Sum = Aggregate (l.values, (a,b) => {return a + b;});
It is called implicitly type parameter list.
You can simplify it more further :
Sum = Aggregate (l.values, (a,b) => a + b);
You can read : given a and b, return a + b
- Extension method
You can extend new method to instance of any class either FCL classes or custom classes.
For example you can extend your own method to string instance.
- Object Initialization expression
You can initialize object and assign value to its parameters with single line of code.
- Anonymous type
You can create anonymous class with its properties and values.
- Query expression
This is LINQ query expression.
Here is the example :
var customers = new []{
new { Name = "anto", age = 15 },
new { Name = "sella", age = 20 },
new { Name = "rudi", age = 30 }
};
You can get customer list that has age over 18 by expressing this query expression :
Var expr = from c in customers
Where c.age > 18
Select c.name;
Foreach(var x in expr)
{
Console.WriteLine(x);
}
Let’s try it to get some exciting experience with these cool features.