C# – new in Visual Studio 2008 vs 2005 or C# 3.0 vs C# 2.0

.net-2.0.net-3.0cvisual-studio-2005visual-studio-2008

I was browsing the Hidden Features of C# question and thought I would try out one of the features I was unfamiliar with. Unfortunately I use Visual Studio 2005 and the feature in question was introduced later. Is there a good list for new features in C# 3.0 (Visual Studio 2008) vs. C# 2.0 (Visual Studio 2005)?

Best Answer

This is not a comprehensive list but these are some of my favorite new features of C# 3.0:

New type initializers. Instead of saying this:

Person person = new Person();
person.Name = "John Smith";

I can say this:

Person person = new Person() { Name = "John Smith" };

Similarly, instead of adding items individually, I can initialize types that implement IEnumerable like this:

List<string> list = new List<string> { "foo", "bar" };  

The new syntax for lambda expressions is also nice. Instead of typing this:

people.Where(delegate(person) { return person.Age >= 21;);

I can type this:

people.Where(person => person.Age >= 21 );

You can also write extension methods to built in types:

public static class StringUtilities
{
    public static string Pluralize(this word)
    {
       ...
    }
}

Which allows something like this:

string word = "person";
word.Pluralize(); // Returns "people"

And finally. Anonymous types. So you can create anonymous classes on the fly, like this:

var book = new { Title: "...", Cost: "..." };