New Features in C# Part I (C# 2.0)

I was researching new C# 4.0 features and thought about aggregating C# 2.0 and C# 3.0 features for completeness,

1. Generics: This is the major addition to the C# language in the 2.0 release. Usually when we define a type, we work with a lot of other types. What generics allows us to do is let the client code specify what types our class with work with.

        // Define type A
        public class A {
            string s;   // Requires type string
            public void Method(string s) { this.s = s; }    // Only works with type string!

        // Change to a generic type
        public class A<T> {
            T t;    // Type will be set by client
            public void Method(T t) { this.t = t; }     // Works with any type!


Generics are specifically useful in building custom collections. This is due to two reasons,

  • Your collection class can work with different types, that is, it could be a collection of ints or a collection of strings, the client can decide this without you having to change any code.
  • You don’t incur the penalties of boxing/unboxing.

        // When you put anything into an ArrayList it gets boxed into an object
        ArrayList a = new ArrayList();

        // Adding an int to this List will not cause boxing!
        List<int> b = new List<int>(); 
2. Iterators: Easily enable the useful foreach construct for your custom collection. Note the new yield keyword, when the yield return statement is reached, the current location is stored. Execution is restarted from this location the next time the iterator is called.
        public class DaysOfTheWeek : System.Collections.IEnumerable {
            string[] m_Days = { "Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat" };

            public System.Collections.IEnumerator GetEnumerator() {
                for (int i = 0; i < m_Days.Length; i++) yield return m_Days[i];
        // Usage:
        DaysOfTheWeek week = new DaysOfTheWeek();
        foreach (string day in week) { }
3. Partial Classes: Allows you to split a single type into multiple type definitions.
        // Before we had to do this,
        public class A
            public void MethodA() { }
            public void MethodB() { } 

        // Now we can construct the class in parts,
        public partial class A
            public void MethodA() { }

        public partial class A
            public void MethodB() { }

4. Nullable Types: Value-type variables can now be assigned the value null.

        int? i = 0;

        i = null;   // allowed to set int to null!

        // Usage:
        int j = i.GetValueOrDefault();
        // or,
        if (i.HasValue) k = i.Value;

    ?? operator:
        int m = i ?? -1;    // if i is null, set m to -1

5. Anonymous Methods: Anywhere you need a delegate (that encapsulates a method), you can now simply insert the method body. Anywhere a delegate is expected, a code block can be used instead: there is no need to define a new method.
        // If we have a delegate,
        delegate void MyDelegate();
        // Previously we would have to use a named method,
        MyDelegate d = a.MethodB;
        // Now we can use an anonymous method,
        MyDelegate d = delegate() { /* Do work; */ };
6. Static Classes: A static class

  • cannot be instantiated
  • cannot be inherited from (they are sealed)
  • can contain one parameterless static constructor (no instance constructors)
  • can contain only static methods.
        static class A {
            static A() { }
            public static void MethodA() { }
            public static void MethodB() { }
7. External Assembly Alias (extern keyword): Now import C++ dlls!
        public static extern int MessageBox(int h, string m, string c, int type);
8. Property Accessor Accessibility: Now get and set on the same property can have different accessability.

        public string Name
            public get { return name; }
            protected set { name = value; }

9. Covariance and Contravariance in Delegates
     Covariance: Return type can now be a derived class, that is, a delegate that encapsulates a method with return type A can also encapsulate a method that returns any derived type of A.
     Contravariance: Params can now be a base class, that is, a delegate that encapsulates a method that takes a param of type B can also excapsulate a method that takes a param that is a base type of B.
        // Say B derives from A,
        public class B : A { }

        // If we have a delegate that returns type A,
        delegate A MyDelegate(B b);

        // It can also encapsulate a method that returns B (dervied class)
        // Even though the delegate signature says that the return type should be A
        MyDelegate m = MethodThatReturnsTypeB;  // Covariance!

        // It can also encapsulate a method with a param A (base class)
        // Even though the delegate signature says that param should be type B
        MyDelegate n = MethodWithParamTypeA;  // Contravariance!

10. Simplified use of Delegates
  • No need to construct a delegate object explicitly,
        // Previously
        MyDelegate d = new MyDelegate(a.Method);

        // Now 
        MyDelegate d = a.Method;

  • Define a method inline,
        Thread t = new Thread(delegate(Object obj) { /* Do Work */ });

  • If params are not used,
        Thread t = new Thread(delegate { /* Do Work */ });
11. Friend Assemblies: An assembly can give access to its internal types/members via the InternalsVisibleToAttribute attribute. Note that private types/members remain private.
        // Mark class A with this attribute, so that B can access internal types/members
        [assembly: InternalsVisibleTo("B")]


12. Inline warning control: A new preprocessor directive has been added to enable/disable compiler warnings.       
        // No need for the CS prefix
        #pragma warning disable 414, 3021

Digg This

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 I (C# 2.0)

  1. Pingback: New Features in C# Part II (C# 3.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: Logo

You are commenting using your 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: