jister
jister

Reputation: 145

c# class that requires action as variable

I have a c# program and I want to make a methodthat looks something like this

 public xx(??? a)
 {
     a.execute();
 }

then I want to call:

xx(Process.Start("notepad.exe", @"C:\Users\Programmer\Documents\Visual Studio 2012\Projects\Key Logger\Output\Log.txt"));

and then have it do that. I have no idea if something like this is accomplish-able, I am rather new to c#.

Upvotes: 0

Views: 108

Answers (3)

Viktor Lova
Viktor Lova

Reputation: 5034

Try this:

public xx(Action a) {
}

xx(() => Process.Start("notepad.exe", @"C:\Users\Programmer\Documents\Visual Studio 2012\Projects\Key Logger\Output\Log.txt"));

More info: lambda expression, delegate tutorial

Upvotes: 1

Guffa
Guffa

Reputation: 700840

Use the Action type for a parameterless delegate:

public xx(Action a) {
  a();
}

There is nothing that would turn a method call into a delegate, the compiler would just expect the method to return a delegate. You can use a lambda expression to easily create a delegate:

xx(() => Process.Start("notepad.exe", @"C:\Users\Programmer\Documents\Visual Studio 2012\Projects\Key Logger\Output\Log.txt"));

Upvotes: 1

Alexei Levenkov
Alexei Levenkov

Reputation: 100630

Maybe Action is what you are looking for:

public xx(Action a)
{
  a();
}

xx(()=> Process.Start("notepad.exe", @"C:\\Output\Log.txt"));

Upvotes: 2

Related Questions