Thursday, February 19, 2009

Extension Methods - Features of C# 3.0 (Part - 1)

I have asked many people about the latest changes brought in C# and many give me a blunt “I don’t know” as an answer. Even they are not aware that C# has a 3.0 version. So I decided to write a series of blog through which I would try to explain some of the prominent features/changes introduced in C# 3.0. One of the features introduced in 3.0 version of C# is Extension Methods. So what is extension methods.

What is Extension Methods?

While working with system classes like int, double, string etc or any third party library you may have wished that it would be nice to have some methods or there should be some facility where by one could add the method you wished to the base class library so that in your project you can use them as if they belong to the base class library. If you have wished something like this then your wish can be fulfilled by Extension Methods. Extension methods in simple terms are adding user defined methods to base classes/types which can be used as an intrinsic methods of the base classes/types. Extension methods are not limited to only system classes they can be added to any classes. For e.g. if you want to add your own method to some third party dll you can very well do it using extension methods. Lets take an e.g. to understand this concept. The best e.g. would be to have a method to check whether a number is even or not, also we will have another “Add” method on int datatype which will keep on adding the numbers to the current value.

How to implement Extension Methods?

We want to implement two extension methods, “IsEvenNo” and “Add”, on int datatype to check whether the value is an even number or not and also a method to add numbers respectively. Extension methods can be implemented using static class, static method and this keyword. The code to implement Extension methods is shown below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExtensionMethodsDemo
{
    public static class ExtensionMethodEg
    {
        public static bool IsEvenNo(this int i)
        {
            return i % 2 == 0 ? true : false;           
        }       

        public static int Add(this int i, int numberToBeAdded)
        {
            return i += numberToBeAdded;
        }
    }
}


One can declare extension methods only through static class and static method. What the “this” keyword in the function argument does, is that it adds the “IsEvenNo” and “Add” method to the first parameter’ type/class. The “this” keyword gives instruction to the compiler to add the method to the int datatype. The extension method can access all the public members, methods and events of the class on which they have been implemented, in this case the int datatype. The static method which acts as an extension method can be used as normal static method as well. Please note that the this keyword can be used only with the first parameter and cannot be used along with the subsequent parameters. One can use any number of parameters in the extension methods but as said earlier the this keyword can be used only with the first parameter. Using the this keyword with other parameters will throw the following compile time error.

“Method 'Add' has a parameter modifier 'this' which is not on the first parameter”

To use the extension method in your code all you need to do is add the namespace to your class file by making use of the “using” keyword. The code is given below.

using ExtensionMethodsDemo;

Once you have added the namespace into your class the intellisense of Visual Studio (VS) shows it as a method of the int datatype as shown in the below screenshot. The blue downward facing arrow before the method in the intellisense gives the hint that it is an extension method.

VS intellisense showing the extension method.

With extension methods we can append user defined methods to any classes let it be a base class library class or a third party class without having to know what lies in the base source code. A simple way to extend the capabilities of classes with user required functions.

The below code shows the "Main" program where extension methods have been used.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ExtensionMethodsDemo;

namespace ExtensionMethods
{
    class Program
    {
        static void Main(string[] args)
        {
            int j = 4;
            bool flag = j.IsEvenNo();
            Console.WriteLine("{0} is a/an {1} number.", j.ToString(), j.IsEvenNo() == true ? "even" : "odd");
            j = j.Add(11);
            Console.WriteLine("{0} is a/an {1} number.", j.ToString(), j.IsEvenNo() == true ? "even" : "odd");
            Console.ReadLine();
            int aa = 4;
            Console.WriteLine(aa.Add(566).ToString());
            Console.ReadLine();
        }
    }
}


How does the compiler know that the extension methods needs to be added as a function in the specified class?

When the code with extension method is compiled the compiler adds an extra attribute to the Intermediate Language (IL) to differentiate the method as an extension method. The following attribute is added.

System.Runtime.CompilerServices.ExtensionAttribute

The IL for the extension method implemented above is given below.

ILDASM showing the extension compiler attribute

Where extension methods have been used in the base class library?

Language Integrated Query or LINQ in short is making use of extension methods extensively. Some of the e.g. of LINQ related extension methods are Where(), Select(), Average(), Max() etc. These methods reside in the System.Linq namespace.

Extension methods is a great feature which helps us to include our own methods to the base class library classes or third party classes. I have seen in many sites people asking can the same extension feature be implemented in properties, events etc?. The answer is no, there is no concept of extension properties, events etc. As the name suggests it can only be implemented to methods.

Also what extension methods does, is, it doesn’t add the method to the base class library, behind the scene the compiler does the necessary hook up mechanism to call the method from your static class and makes it appear as an integral part of the base class library. The compiler does the back end work for you by calling the static method from the static class.

In the next blog we will see another feature of C# 3.0 know as Automatic Properties.

Know More

Sandeep

2 comments:

  1. Nice post Sandeep.

    I would like to add the following:

    If an extension method has the same signature as a method which is already defined for the type, then that extension method will never be called for that type.

    ReplyDelete

Please provide your valuable comments.