Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# how to assign Console.WriteLine to variable

Tags:

c#

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...

like image 578
MTo Avatar asked Nov 30 '22 11:11

MTo


2 Answers

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).

like image 52
Servy Avatar answered Dec 10 '22 07:12

Servy


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.

like image 32
Sergey Kalinichenko Avatar answered Dec 10 '22 06:12

Sergey Kalinichenko