New Features in C# Part II (C# 3.0)

[Related Posts: Part I (C# 2.0) and Part III (C# 4.0)]

C# 3.0 introduces some important changes to the language (like LINQ), and some cosmetic changes designed to make coding simpler and more readable. Here are some of the new changes in C# 3.0,

1. Implicitly typed local variables and arrays:  A new keyword is introduced called var. This allows you to declare a variable and let the compiler figure out the type

        // Declare a variable of type int
        var i = 5;

        // Declare an int array
        var a = new[] { 1, 10, 100, 1000 };

        // Usage:
        for (var i = 0; i < 5; i++) { }
        foreach (var item in MyList) { }
        using (var file = new StreamReader("Filename.txt")) { }
 

2. Auto-implement properties: Use this when no additional logic is required in the property accessors.

        // Previously we had to do this,
        private string _name;
        public string Name
        {
            get { return this._name; }
            set { this._name = value; }
        }
 
        // Now we can shorthand it, there’s no need to declare the _name variable
        public string Name { get; set; } // The compiler creates a private anonymous backing field
 

3. Object and collection initializers: Set properties inline during object creation.

        public class A {
            public string Name { get; set; }
            public string Address { get; set; }
        }
 
        // Previously we would have to do,
        A a = new A();
        a.Name = "...";
        a.Address = "...";

        // Now we can do this,
        A a = new A { Name = "...", Address = "..." };

        // Similarly, we can initialize collections,
        List<int> MyList = new List<int> { 0, 1, 2, 3, 4 };
 

4. Extension methods: Now you can add methods to existing types without creating a new derived type, recompiling or modifying the original type’s code. This is incredibly useful in writing cleaner code,

        // Previously we would do this,
        String domain = GetDomain(url); // url is a string type

        // Now we can do this,
        String domain = url.GetDomain();  // String now has a custom method ...

        // ... because we defined an extension method for the string type,
        public static class MyStringExtensions {
            public static String GetDomain(this String str)
            {
                // Extract domain from url and return;
            }
        }

5. Anonymous types: If you need a small class with read only properties, you can now use a simple syntax,

        // a is an anonymous type, the compiler creates the class with 
        // private string fields _name and _address 
        // and public string properties Name and Address,
        var a = new { Name = "...", Address = "..." };

        // a.Name and a.Address are read-only,
        string s = a.Name;
 

6. Lambda expressions: A new operator => is introduced called “goes to”. The left side of the operator specifies an input param and the right side is the expression or statement block.

        // A delegate can be initialized with a lambda expression
        MyDelegate d = () => { /* Do Work */ };
 

7. Query keywords (LINQ): We are now able to use TSQL like syntax inside C# to query data sources (could be objects, collections, XML, or SQL databases). Introduces a host of new keywords like from, where, select, group, orderby, join, etc.

        // The data source,
        int[] numbers = { 0, 1, 2, 3, 4, };

        // Create the query,
        var lessthan3 =
            from num in numbers
            where num < 3
            select num;

        // Output: 0 1 2
        foreach (var m in lessthan3) {
            Console.Write(m.ToString() + " ");
        }
 

8. Partial method definitions: A partical class (introduced in C# 2.0, see here) can now have partial methods. This simply means the method signature is in one partial class and the implementation in another. There are some constraints, like the method is implicitly private (and therefore cannot be virtual) and must return void.

        public partial class A {
            // Method definition
            partial void Method();
        }

        public partial class A {
            // Method implementation
            partial void Method() { /* Do Work */ }
        }

Digg This
Advertisements

About soumya chattopadhyay
I live and work in Seattle, WA. I work with Microsoft technologies, and I'm especially interested in C#.

2 Responses to New Features in C# Part II (C# 3.0)

  1. Pingback: New Features in C# Part I (C# 2.0) « I.Net

  2. Pingback: New Features in C# Part III (C# 4.0) « I.Net

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: