We have static methods:

String someString = "someString"; Console.Writeline(someString); Console.ReadKey(); 

Can we add a static method to the Console class via extension methods? For example:

 Console.DoSomething(); 
  • And what is it for? What is the purpose of extending the Console class? - Vadim Prokopchuk
  • No goal. Just gave an example with the console. I need to add a static mouse click method to the Cursor class: Cursor.Click (); - J.John
  • static void Click(this Cursor cursor) { } , provided that the Cursor not a static class. - Vadim Prokopchuk
  • 2
    If you need such functionality, then vote for it on the visual studio user voice and in future versions of C # with sufficient support this functionality may appear. - Vadim Ovchinnikov February
  • This is not done for the time being because you can easily write the “neighboring” static class CursorEx , in which you define the necessary methods. With instance methods such a trick without static methods would be more difficult. - VladD

1 answer 1

No you can not. Extension methods require passing instances of classes to them (those that are passed by the first parameter and are preceded by the this modifier, it is to these instances that the "extension" is applied), while the Console is a static class.

  • Is it possible to do this some other way? - J.John
  • with the same syntax is impossible. You can only add your own wrapper class, static or normal, add the necessary methods to it and use it already. But this does not apply to extension methods (however, extension methods are nothing more than syntactic sugar, which does the same). - DreamChild