Reputation: 145
Its possible to do
using System;
Action action = new Action(Console.WriteLine);
action(); //will write a empty line
but is there a way to pass a method with parameters e.g.
using System;
Action action = new Action(Console.WriteLine("Hello World")); //This doesn't work
action(); //want it to write a line which will say "Hello World"
Upvotes: 0
Views: 108
Reputation: 321
You can use generic action like this
Action<string> writeLine = Console.WriteLine;
writeLine("hello");
Upvotes: 0
Reputation: 1936
Try this:
Action action = new Action(() => Console.WriteLine("Hello World"));
or as mentioned @JeroenMostert
Action action = () => Console.WriteLine("Hello World");
Upvotes: 3
Reputation: 176896
you can do like this also
Action<int> print = ConsolePrint;
print(10);
static void ConsolePrint(int i)
{
Console.WriteLine(i);
}
or you can do this also
Action<int> print = (i)=> Console.WriteLine(i);
print(10);
Upvotes: 0