Asdar
Asdar

Reputation: 145

Is there a way to pass a method WITH parameters as a new action?

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

Answers (3)

Mustafa Çetin
Mustafa Çetin

Reputation: 321

You can use generic action like this

Action<string> writeLine = Console.WriteLine;
writeLine("hello");

Upvotes: 0

Oleksii Klipilin
Oleksii Klipilin

Reputation: 1936

Try this:

Action action = new Action(() => Console.WriteLine("Hello World"));

or as mentioned @JeroenMostert

Action action = () => Console.WriteLine("Hello World");

Upvotes: 3

Pranay Rana
Pranay Rana

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

Related Questions