I’m trying to create an overload of the System.Console.ReadLine() method that will take a string argument. My intention basically is to be able to write
string s = Console.ReadLine("Please enter a number: ");
in stead of
Console.Write("Please enter a number: ");
string s = Console.ReadLine();
I don’t think it is possible to overload Console.ReadLine itself, so I tried implementing an inherited class, like this:
public static class MyConsole : System.Console
{
public static string ReadLine(string s)
{
Write(s);
return ReadLine();
}
}
That doesn’t work though, cause it is not possible to inherit from System.Console (because it is a static class which automatically makes is a sealed class).
Does it make sense what I’m trying to do here? Or is it never a good idea to want to overload something from a static class?
Just wrap the console in your own class and use that instead. You don’t need to inherit for that:
Then you can go ahead and use that one in your program instead:
If you wish to push it a bit further and make
MyConsolea bit more flexible, you could also add support to replace the input/output implementations:This would allow you to drive the program from any
TextReaderimplementation, so commands could come from a file instead of the console, which could provide some nice automation scenarios…Update
Most of the methods that you need to expose are extremely simple. OK, a bit tedious to write perhaps, but it’s not many minutes of work, and you need to do it only once.
Example (assuming we are in my second sample above, with assignable reader and writer):