I Would like to shorten typing Console.WriteLine and assign it to var for example: var write = Console.WriteLine(); and execute it like write("My name is.."); >>>output>> My name is...
Assigning a method to a variable is done though the use of a delegate:
Action<string> write = Console.WriteLine;
write("Hello World!");
Of course the delegate won't be able to represent every single overload of Console.WriteLine
(and it has 18 of them). It can only represent one of the overloads (but it can represent any one of those 18).
Although doing it simply to shorten your code is a questionable idea, here is what you can do: define a delegate for the Write
method, like this
delegate void WriteDelegate(string msg, params object[] args);
Define a variable of type WriteDelegate
, and assign Console.Write
to it:
private static readonly WriteDelegate w = Console.Write;
Now you can use w
to call Console.Write
, with or without parameters:
w("Hello");
w(", {0}", "world!");
Demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With