0

There is an easy way for adding method to an existing class:

public void ExtendingObject(this Me self, ...) { ... }

(new Me()).ExtendingObject(...)

But is there a way to add extension on a class side (ie. as a static method) ?

public void ExtendingClass(??? Me self, ...) { ... }


Me.ExtendingClass(...)

I am thinking to using it to add behavior to an Enum

public enum ErrorCode { ... }

ErrorCode.BuildFrom(123)
mathk
  • 7,973
  • 6
  • 45
  • 74
  • http://social.msdn.microsoft.com/Forums/en-US/c0884849-c10c-49b8-9ea4-5ca1d723576e/create-static-extension-methods-for-types?forum=vcsharp2008prerelease – w.b Mar 11 '14 at 15:19
  • This is a better question than the one it's a duplicate of, I think, but the other one is answered already. – Bobson Mar 11 '14 at 15:20
  • @Bobson why better? This is exactly the same question. – Shadow The GPT Wizard Mar 11 '14 at 15:21
  • @ShadowWizard - This one shows more work and what the desired result is. – Bobson Mar 11 '14 at 15:24
  • _"adding method to an existing class"_... **No**, it defines an operation _on_ existing _type_. The type doesn't have to be a class and the method is not _in_ the type it extends. – Tom Blodget Mar 11 '14 at 22:24
  • @TomBlodget Define what do you mean by "in". What useful semantic part of "in" do you put to affirme that it is not in the type it extends. – mathk Mar 12 '14 at 10:01
  • @mathk Yes, it is semantics but it is important to understand that an extension method is not a member of the .NET type that it extends. It can't be discovered by inspecting the type and it doesn't have access to private and protected (and in many cases, internal) members of the type. That's why I avoid using the word "in" and avoid saying "adding method to a class". More succinctly, an extension method is _in_ the class and assembly in which it is defined and implemented; It is not _in_ nor _added to_ the type of its `this` parameter. – Tom Blodget Mar 12 '14 at 11:22
  • Take the perspective of the type checker. The method extension is look as it was in the type. And I am pretty sure that the runtime add the method to the method dictionary of the type. Even if `this` parameter as some form of restriction it is still the object receiving the message. Method extension have been there for a will in other language and they are considered in the type. And saying type is just to avoid saying that C# is not a consistent language regarding object. – mathk Mar 12 '14 at 13:24
  • See the [C# spec](http://go.microsoft.com/fwlink/?LinkId=199552); It's quite readable. There are two sections: defining extension methods and invoking extension methods. Play with the compiler and disassembler to compare the IL. [LINQPad](https://www.linqpad.net/CodeSnippetIDE.aspx) is very convenient for this. – Tom Blodget Mar 12 '14 at 23:49

0 Answers0