I have to type Console.WriteLine() many times in my code. Is it possible to create a shortcut for Console.WriteLine so that I can use it like...
CW=Console.Wr
You could no doubt create a Visual Studio snippet for it (although actually there's one already for cw
, apparently - try it!).
I would personally suggest that you don't use a shortcut within the code - it's likely to be clearer to anyone reading it if it still says Console.WriteLine
.
Depending on what this is for, it may make sense to write a helper method called, say, Log
- that has a reasonable meaning, whereas CW
doesn't.
(If this is for logging, consider using something more powerful such as log4net, too.)
If you have ReSharper you can type out and Enter and the row
Console.Out.WriteLine("");
will be written.
In case you want to output a variable there is another live template: outv.
Console.Out.WriteLine("time = {0}", time);
Here time is a variable which you could select after typing outv.
Write a method which returns void and call it for Console.WriteLine()
.
void Log(string msg)
{
Console.WriteLine(msg);
}
Visual Studio already has a default code snippet for this. Just type cw
and press tab. Note that if you're considering using a method, it may lack some features like the automatic string.Format and other overloaded parameters.
You could declare a static method to wrap the call:
static class C
{
static void W(string s)
{
Console.WriteLine(s);
}
}
then:
C.W("Print Something");
I would be inclined to use the "inline method" refactoring before checking in any code that calls this method. As Jon Skeet notes, it's less confusing simply to use Console.WriteLine directly.
This shortcut will avoid exceptions being thrown when you use a composite formatting overload like Console.WriteLine(String, Object[])
and the number of format items in format
and the number of items in the argument list, args
, differ:
public bool WriteToConsole(string format, params object[] args)
{
var succeeded = false;
var argRegex = new Regex(@"\{\d+\}");
if ((args != null) && (argRegex.Matches(format).Count == args.Length))
{
Console.WriteLine(format, args);
succeeded = true;
}
else
{
Console.WriteLine(format);
}
return succeeded;
}