1

I want to create a custom method that will work when added after “Console” in c#. It would be sort of similar to Console.WriteLine().

It would look something like this: Console.PrintMyName(). And when it is called, it would do this: Console.WriteLine(“James”).

Is there some way to do this by defining a function that only works as a method when put after after “Console”.

Kit
  • 20,354
  • 4
  • 60
  • 103
  • Have a look at this [related](https://stackoverflow.com/questions/249222/can-i-add-extension-methods-to-an-existing-static-class) post. – Axel Kemper Mar 14 '21 at 01:22

1 Answers1

3

In short, no.

The closest thing you can do is approximate what you want.

The Console class (System.Console specifically) is a static class and so cannot have "methods added to it" in the same way as a class that can be instantiated (instantiated classes can have extension methods).

The closest you can come to this is to either

  • create your own class named Console with it's own PrintMyName method. However, if you use both System.Console and your custom MyCustom.Console in the same compilation unit, you will have to disambiguate them by addressing one or both by their full namespace.
  • create a new static class with a completely different name.
Kit
  • 20,354
  • 4
  • 60
  • 103
  • Thanks for the info. How would I add a method to a non static class? For example how can I add a method to a WinForms control like: tabControl1.myCustomMethod() – user9719238713 Mar 13 '21 at 22:16