Logo 
Search:

C# FAQ

Submit Interview FAQ
Home » Interview FAQ » C#RSS Feeds

What's new in C# 3.0?

  Shared By: Luigi Fischer    Date: Nov 26    Category: C#    Views: 1012

Answer:

Support for LINQ was the driving force behind the main enhancements in C# 3.0. Query expressions are the most obvious example, but lambda expressions, extension methods and anonymous types also fall into this category. However most of these enhancements are useful beyond LINQ.

Query expressions allow a SQL-like query syntax to be used in C#, e.g.

var nameList = new List<string> { "jack", "jill", "sue" };

var results = from name in nameList
where name.StartsWith("j")
select name;
Query expressions are just syntactic sugar - they resolve to standard method calls. For example the query expression above can be rewritten as:

var results = nameList.Where(name => name.StartsWith("j"));
The argument to Where() is a lambda expression, which represents an anonymous method. However a lambda expression is not just a more concise way to represent executable code - it can also be interpreted as a data structure (known as an expression tree), which allows the expression to be easily analysed or transformed at runtime. For example, LINQ-to-SQL makes use of this feature to transform C# queries to SQL queries, which gives much better performance than a simple in-memory filtering of results (as offered by DataTable.Select(), for example).

The Where() method shown above is an example of another new C# 3.0 feature: extension methods. Extension methods allow extra methods to be 'attached' to an existing type - any type, even sealed types or types you don't have the source code for. For example, the Where() method can be applied to any type that implements IEnumerable<T>.


Another new feature of C# 3.0 is the var keyword, which allows the compiler to infer the type of a variable from context, which is required for anonymous types but can be used with standard named types too:

var list = new List<string>() { "jack", "jill", "sue" }; // optional use with named types

var person = new { name = "jack", age = 20 }; // anonymous type
These examples also demonstrate the new object initializer and collection initializer syntax.

Finally, there are implicitly typed arrays and auto-implemented properties:

var names = new [] { "jack", "jill", "sue" }; // implicitly string[]

public string Name { get; set; } // auto-implemented property - private backing field auto-generated

Share: