Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to write extension methods for Console? [duplicate]

While looking at this question and it's answers I thought that it would be a good idea to write an extension method for System.Console that contained the desired functionality.

However, when I tried it, I got this compiler error

System.Console': static types cannot be used as parameters

Here's the code:

using System; using System.Runtime.CompilerServices;  namespace ConsoleApplication1 {     public static class ConsoleExtensions     {         [Extension]         public static string TestMethod(this Console console, string testValue)         {             return testValue;         }      } } 

Is there another way of creating extension methods for static types? Or is this just not possible?

like image 864
CoderDennis Avatar asked Oct 31 '09 20:10

CoderDennis


People also ask

Is it possible to add extension methods to an existing static class?

No. Extension methods require an instance variable (value) for an object.

Can we define extension methods for class which itself is a static class?

Extension methods are defined as static methods but are called by using instance method syntax. Their first parameter specifies which type the method operates on. The parameter is preceded by the this modifier.

Is it possible to achieve method extension using interface?

Of course they can; most of Linq is built around interface extension methods.

Do extension methods have to be static?

An extension method must be a static method. An extension method must be inside a static class -- the class can have any name. The parameter in an extension method should always have the "this" keyword preceding the type on which the method needs to be called.


2 Answers

It's not possible, as mentioned in Matt's answer.

As a workaround you could create a static class that will wrap Console adding desired functionality.

public static class ConsoleEx {     public static void WriteLineRed(String message)     {         var oldColor = Console.ForegroundColor;         Console.ForegroundColor = ConsoleColor.Red;         Console.WriteLine(message);         Console.ForegroundColor = oldColor;     } } 

It's not ideal, as you have to add that little "Ex", but flows with code decently well, if that's any (ehm) consolation:

ConsoleEx.WriteLineRed("[ERROR]") 
like image 103
Sebastian K Avatar answered Oct 04 '22 04:10

Sebastian K


No it's not possible unfortunately. See Static extension methods

A few people have suggested it: http://madprops.org/blog/static-extension-methods/

...but it was never done in .NET 4. Apparently extension properties got someway to making it but was then abandoned.

https://blogs.msdn.com/ericlippert/archive/2009/10/05/why-no-extension-properties.aspx

like image 33
Matt Breckon Avatar answered Oct 04 '22 04:10

Matt Breckon