New Language Features in C# 3.0

New Language Features in C# 3.0


C# 3.0 adds several new language features.  In this article I will review Auto Implemented Properties, Object Initializers, Collection Initializers, Local Variable Type Inference, Language Integrated Query (LINQ) and Anonymous Types. 

I picked up this material from an excellent video by Luke Hoban.

Auto Implemented Properties

public string CustomerID { get; set; }

The private variable is no longer necessary.

Object Initializers

Customer cust1 = new Customer()

{ CustomerID = "ALKI", ContactName = "Marcel" };

Even if a method doesn't have an overload which lets you fill in some properties right away, you can use the Object Initializer to accomplish the same thing.

Collection Initializer

new List<Customer>() { cust1 };

As above but for collections.

Local Variable Type Inference

var customers = new List<Customer>();

How sweet is this?!  But, only for local types.  You won't be doing this with class level variables.

Language Integrated Query (LINQ)

Enumerable.Where(customers, c=> == "London");

customers.Where(c=> == "London");

var query = from c in customers

where c.City == "London"

Select c;

Where is an extension method

LINQ uses Lambda expressions.  Here c=> == "London" is the Lambda expression.  The => is read "goes to."

LINQ can be used to query against XML, objects or SQL.

Anonymous Type

The neat thing about anonymous types is that you can create a type on the fly with no name/type, hence anonymous.  This new type can have a different number of properties than the query source.  For example, say you're doing a query on the customer object, the query result can be set up to only contain the customer ID and name.

Var query ...

select new

{  CustomerID = c.CustomerID,

   ContactName = c.ContactName };

// the property names above are optional, if not specified the property name of source object is used.