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
If you write this at the top of the page:
using j = System.Console;
then at any time, you can use
j.WriteLine("Anything you want to write");
And that's all.
By the way, you can use anything instead of the "j".
To piggyback on Michael Stum's answer, we could also make object
as the type parameter to Action
delegate like so:
Action<object> cw = x => Console.WriteLine(x.ToString());
I usually do that on my C# Interactive window to quickly print out objects that I'm working with.
For example:
> var grid = driver.FindElements(By.XPath("//div[@class='ReactVirtualized__Grid__innerScrollContainer']//div"));
> cw(grid);
System.Collections.ObjectModel.ReadOnlyCollection`1[OpenQA.Selenium.IWebElement]
>
// For formatting string and parameters define a function
// The shortcut function wl, kind of write line
public void wl( string format, params object[] parms){
Console.WriteLine(format, parms);
}
// Just for strings we can use Action delegate
Action<string> ws = Console.WriteLine;
// examples:
ws("String with no formatting parameters");
wl("String without formatting parameters");
wl("String with {0} parameters {1}", 2, "included");
wl("several parameters {0} {1} {2} repeated {0}", 1234, 5678, 6543);
or using extension method: formatString.wl(arguments...)
public static class ConsoleWriteExtensions
{
public static void wl(this string format, params object[] parms){
Console.WriteLine(format, parms);
}
}
"{0} -> {1}".wl("Mili",123.45); // prints Mili -> 123.45
If you want it global, you could write an extension method:
public static class StringExtensions
{
public static void ConLog(this string msg)
{
Console.WriteLine(msg);
}
}
Now wherever you are, you can call "My Message".ConLog();
on any string in your application and write it to the console.
public static void CW(string str)
{
Console.WriteLine(str);
}
One of my favorites also... Coming from BASIC and Python... I missed Print() very often... I also use Print() extensively in JS/ES for console.log/other-consoles often...
So declare it as a function:
public static void Print( object x ){ Console.WriteLine( x ); }
Print( "Hi\n\n" + x.toString() + "\n\nBye!!!" );
Print( $"{x} ~ {y} ~ {z}" );