29 12 2007
Extension methods – how they look like after compiling
This blog entry is supposed to be the continuation for entry C# Extension Methods where I told what extension methods are and how to use them. This time I will tell about what they are behind the curtains. Do they really add new methods to current classes or not? I mean, are these methods really added to classes or are they something else?
Let’s start with extension that adds Nl2Br() method to string. This function is well-known from PHP programming language. So, here’s the code.
public static class Ext
public static string Nl2Br(this string s)
return s.Replace("\r\n", "<br />")
.Replace("\n", "<br />");
static void Main(string args)
string s = "blah\r\nblah";
Now when we look the methods of string we will see Nl2Br() method also there.
That’s right, we see this method there but we cannot be sure if it is really there. So, is this new method illusion or real? Let’s compile our code and see what it looks like in intermediate language.
.method private hidebysig static void Main(string args) cil managed
// Code size 26 (0x1a)
.locals init ( string s)
IL_0001: ldstr "plah\r\nplah"
IL_0008: call string csharptest.Ext::Nl2Br(string)
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0013: call string [mscorlib]System.Console::ReadLine()
} // end of method Program::Main
Look at the line where Nl2Br() is called. As we can see Nl2Br() method is not part of string class. Compilator translates all calls to extension methods to calls to static class methods. So, telling that compiler creates new methods to classes is completely wrong as we just saw.