Archive for October 23, 2011

Inside C# Extension Methods

Posted: October 23, 2011 in .NET, C#
Tags: ,

C# Extension methods were introduced in C# 3.0. They provide a mechanism to extend(not the inheritance way) the functionality of an existing class by attaching methods to it.An extension method needs to be developed in a static class as a static method as shown below:

public static class MyExtensions 
    { 
        public static Int32 AddExt(this Int32 i, Int32 j) 
        { 
            return i + j; 
        } 
    }

We can invoke it as

10.AddExt(12)

In this post we will look at what’s happening inside extension method.

To understand the difference I am adding one more static method of exactly same signature.

public static class MyExtensions 
    { 
        public static Int32 AddExt(this Int32 i, Int32 j) 
        { 
            return i + j; 
        } 
        public static Int32 AddStatic(Int32 i, Int32 j) 
        { 
            return i + j; 
        } 
    }

The two methods are invoked as:

static void Main(string[] args) 
        { 
            Console.WriteLine(10.AddExt(12)); 
            Console.WriteLine(MyExtensions.AddStatic(10,12)); 
            Console.Read(); 
        }

Let’s take a look into the IL code of the two method calls.

ext

The IL code of the two method calls are exactly same and they are just static method calls. Only in case of AddExt the object on which it is invoked in C# code is passed as first parameter value.

So what’s going on ? We have to go to the IL for method definitions:

image

image

Only visible difference is the extension method has an attribute called ExtensionAttribute injected on the IL code. Let’s add this attribute to the other static method and see what happens?

This leads to a compiler error “Do not use ‘System.Runtime.CompilerServices.ExtensionAttribute’. Use the ‘this’ keyword instead.”

So Mr. compiler is not allowing us to hack around with his magic wand of syntactic sugar.

However we can summarize as:

  • When we write an extension method using “this” keyword in the first parameter compiler injects a ExtensionMethodAttribute to the IL code of the method.
  • The invoking code for an extension is replaced as <Static Class Name>.<ExtensionMethodName>(<Object Instance on which method is invoked>,…….)

Hang on.. What if there are two classes with same extension method name on same class e.g. if we add something like:

public static class MyOtherExtensions 
    { 
        public static Int32 AddExt(this Int32 i, Int32 j) 
        { 
            return i + j; 
        } 
        public static Int32 AddStatic(Int32 i, Int32 j) 
        { 
            return i + j; 
        } 
    }

We immediately get a compiler error “The call is ambiguous between the following methods or properties: ‘ExtensionMethods.MyExtensions.AddExt(int, int)’ and ‘ExtensionMethods.MyOtherExtensions.AddExt(int, int)

If I define the extension method on a dynamic type as

public static Int32 AddExt(this dynamic i, Int32 j) 
{ 
            return i + j; 
}

Again compiler stops us from so with a message “The first parameter of an extension method cannot be of type ‘dynamic’

We will go for a generic parameter now.

public static Int32 AddExt<T>(this T i, Int32 j) 
        { 
            return ++j; 
        }

This one compiles. But which will be invoked? MyExtensions.AddExt or MyOtherExtensions.AddExt.

static void Main(string[] args) 
       { 
           Console.WriteLine(10.AddExt(12)); 
           Console.WriteLine(new Object().AddExt(12));

           Console.WriteLine(MyExtensions.AddStatic(10, 12)); 
           Console.Read(); 
       } 


public static class MyExtensions 
    { 
        public static Int32 AddExt<T>(this T i, Int32 j) 
        { 
            return ++j; 
        } 
        public static Int32 AddStatic(Int32 i, Int32 j) 
        { 
            return i + j; 
        } 
    } 
    public static class MyOtherExtensions 
    { 
        public static Int32 AddExt(this Int32 i, Int32 j) 
        { 
            return i + j; 
        } 
        public static Int32 AddStatic(Int32 i, Int32 j) 
        { 
            return i + j; 
        } 
    }

It is MyOtherExtensions.AddExt that is compiler finds the closest match while generating the IL Code.

image

So Extension methods are nothing but static calls accepting the object instance on which it is invoked (as if instance method) as the first parameter.

The last question we they can only be added in static classes. I think that’s good design decision.

  • Extension methods are supposed to act & designed like instance method on some other classes
  • We can’t add global methods without classes in C# every method needs a class container
  • But extension methods are not supposed be aware of instance properties of the class they belong to as that is a mere container for them.
  • So best way is to enforce through the complier that extension methods are within static classes