Wednesday, November 29, 2006

FW 3.0 Enhancements

The .Net framework 1.1 was basically a big service-pack for 1.0, and 2.0 brought the Generics concept, but mainly focused on enhancing ASP.Net.

.Net 3.0 does not focus on a specific side of the framework, instead its goal is to enhance the flexibility of the language itself.

Lets have a look at some of these enhancements:

Implicit Variables
As minor as these feature might look, other features like LINQ rely heavily on it.
In C# 3.0, there's a new variable type - var (variant).
When a variable is declared as var, it's type will be chosen by the compiler based on the first variables initialization.
For example:


var x = 5; //the compiler will deal x as a simple int.

The only limitation is, that a variable declared as var must have an initializer,
For example, the next line will produce an error:
var x;

Note: Using implicit variables as a norm is NOT good, not because of performance issues (no boxing is made), but the code is less readable and you get minimum to no design-time support.

Anonymous Types
Following the implicitly typed variables, a complementary step is the ability to create an implicit type.
Lets have a look at the following code:


var myself = new { FirstName = "R", LastName="Stern", HasBlog=true};
var other = new { FirstName = "Slash", LastName="The" HasBlog=false };


I defined 2 implicit variables, and instantiate them as a new type that has 2 string properties and a Boolean.
If we look at the IL generated by this code, we'll get:


class __Anonymous1
{
private T1 f1;
private T2 f2;
private T3 f3;

public T1 FirstName { get { return f1 ; } set { f1 = value ; } }
public T2 LastName { get { return f2 ; } set { f2 = value ; } }
public T3 HasBlog { get { return f1 ; } set { f1 = value ; } }
}


Notice the compiler automatically generated a getter and a setter for each property in our type.
Furthermore, since both variables - myself & other has the same initializers, they are considered of the same type!

Lambda Expressions
Lambda expressions allows us to take anonymous methods to the next level.
Instead of writing these methods in the standard "verbose" way, why not simple describe it?
For example:
Instead of:


// get an array of string items in the collection that equal to 'A'
string[] AStrings = col.FindAs(delegate(string str)
{
if (sItem[0] == 'A')
return true;
else
return false
;
});


Consider the following:

string[] AStrings = col.FindAs(Func<string,bool> f = str => sItem=='A');


I'll continue the post tomorrow with some more examples.

No comments: