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
Comments
  1. sumansaha15 says:

    Nice and crisp article! Would like to add a small point: Extension methods can be used in fwk 2.0 also with a small hack.

    Create a class library named System.Runtime.CompilerServices containing a class with code: [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class |
    AttributeTargets.Method)]
    public sealed class ExtensionAttribute : Attribute { }.

    Add the reference to any 2.0 project and create extension methods like – static int AddInt(this int i, int j)
    {
    return i + j;
    }

  2. Inside C# Extension Methods « Sankarsan’s Journal…

    Thank you for submitting this cool story – Trackback from DotNetShoutout…

  3. […] 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…  .NET, C# Read the full post on DotNetShoutout… […]

  4. […] Inside C# Extension Methods – Sankarsan’s Journal […]

  5. Axel says:

    Thank you for this very good explanation!!

  6. JayPrakashSharma says:

    Very nice and informative post. It provides me comprehensively knowledge about
    Extension Method in c#. Thanks for sharing with us. I’ve checked another post
    while I’m wondering over the internet for related to this post. That post also explained
    very well on Extension Method in C# which I was checked. Here I want to share
    the post link, please visit at once…..

  7. Prakash says:

    Nice Article.. Also came across this article helpful on Extension methods:
    http://www.a2zmenu.com/Blogs/CSharp/CSharp-Extension-Method.aspx

  8. […] Inside C# Extension Methods – Sankarsangoogle_ad_client = "ca-pub-2541293085579121"; /* BNInco… […]

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.