Is it possible to write extension methods for Console?

CoderDennis picture CoderDennis · Oct 31, 2009 · Viewed 10k times · Source

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?

Answer

Sebastian K picture Sebastian K · May 24, 2016

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]")