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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace csharptest
{
public static class Ext
{
public static string Nl2Br(this string s)
{
return s.Replace("\r\n", "<br />")
.Replace("\n", "<br />");
}
}
class Program
{
static void Main(string[] args)
{
string s = "blah\r\nblah";
Console.WriteLine(s.Nl2Br());
Console.ReadLine();
}
}
}
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
{
.entrypoint
// Code size 26 (0x1a)
.maxstack 1
.locals init ([0] string s)
IL_0000: nop
IL_0001: ldstr "plah\r\nplah"
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: call string csharptest.Ext::Nl2Br(string)
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0012: nop
IL_0013: call string [mscorlib]System.Console::ReadLine()
IL_0018: pop
IL_0019: ret
} // 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.