How extension methods are implemented internally

怎甘沉沦 提交于 2019-11-29 10:32:57

As already have said by other colleagues it is just a static method. It is all about the compiler we can say that CLR even have no idea about extension methods. You can try to check IL code ..

Here is an example

static class ExtendedString
{
    public static String TestMethod(this String str, String someParam)
    {
        return someParam;
    }
}

static void Main(string[] args)
{
    String str = String.Empty;
    Console.WriteLine(str.TestMethod("Hello World!!"));
    ........
}

And here is the IL code.

  IL_0001:  ldsfld     string [mscorlib]System.String::Empty
  IL_0006:  stloc.0
  IL_0007:  ldloc.0
  IL_0008:  ldstr      "Hello World!!"
  IL_000d:  call       string StringPooling.ExtendedString::TestMethod(string,
                                                                       string)
  IL_0012:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_0017:  nop

As you can see it is just a call of static method. The method is not added to the class, but compiler makes it look like that. And on reflection layer the only difference you can see is that CompilerServices.ExtensionAttribute is added.

extension methods are converted to static functions.In other words,They are syntactic sugar for static functions.

I dont think that reflection is involved in extension methods. The extension method is handled in the same way like you write a static helper function in a helper class, the only difference is that compiler does it for you.

To clarify the above answer... Extension Methods ARE static functions. The additional features in .NET 3.5 allow them to be interpreted as if they are new methods on the type in question.

Extension methods are just static methods. The only difference is brought by tools such as the Visual Studio editor which pop them up for the auto complete (intellisense) feature. You can find a detailed explanation here: C# Extension Methods: Syntactic Sugar or Useful Tool?

Extension methods are very much like static methods with the only difference in it having an attribute CompilerServices.ExtensionAttribute which helps in identifying it as an Extension method.

You can read this

Yes, extension methods are just static methods. They have no extra privileges with respect to the classes they supposedly "extend". However, the compiler does mark the "extension" static method with an ExtensionAttribute. You can see this in the IL. This makes the compiler treat it specially, so that you cannot actually invoke it as a regular static method. For instance, this won't compile:

var test = new [] { "Goodbye", "Cruel", "World" };
var result = IEnumerable<string>.Where<string>(test, s => s.Length > 5);

Even though this is what happens under the hood.

But as LukeH notes below, you can invoke it on the class where it's actually defined... Silly me.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!