none
Extension Method, how to add a static method to a class RRS feed

  • Question

  • extension method can add an  instance method to a class, is it possible to add a static method to a class?
    thanks!
    Hargen
    Monday, April 27, 2009 1:46 PM

Answers

All replies

  • No.

    Extension method is a syntactic sugar and you don't really change the class you're adding an extension to (you don't add an instance method on a class - it's just looks as you do).
    • Edited by codevanced Monday, April 27, 2009 2:05 PM
    Monday, April 27, 2009 2:02 PM
  • Are there any design reasons for not supporting this feature?
    Hargen
    Monday, April 27, 2009 2:05 PM
  • No.

    Extension method is a syntactic sugar and you don't really change the class you're adding an extension to (you don't add an instance method on a class - it's just looks as you do).

    I don't know if syntactic sugar is the right term for this - syntactic sugar implies that it's just an easier way of doing something you can do in another way, but as far as I know there's no other way to create methods that are regarded as part of an existing class outside of your project.
    Convert between VB, C#, C++, & Java (http://www.tangiblesoftwaresolutions.com)
    Monday, April 27, 2009 2:18 PM
  • Add your vote to this feedback article.
    Hans Passant.
    • Marked as answer by Zhi-Xin Ye Monday, May 4, 2009 12:39 PM
    Monday, April 27, 2009 2:22 PM
    Moderator
  • David,

    I bet you know that for the compiler, extension method is just a method that is marked with System.Runtime.CompilerServices.ExtensionAttribute . You can even introduce your own one (say, if you're working on .NET 2.0 - and thus use extension methods in .NET 2.0).

    I called it syntactic suger because it appears as a call to an instance method, while in reality it's a call to a static method on a completely different type.
    Monday, April 27, 2009 2:32 PM
  • Yeah, I see what you mean - I guess 'syntactic sugar' is pretty subjective anyway.

    Convert between VB, C#, C++, & Java (http://www.tangiblesoftwaresolutions.com)
    Monday, April 27, 2009 2:54 PM