Whyser
Whyser

Reputation: 2247

Calling lambda expression directly? (Ex. Action.Invoke(()=>{})

Sorry for the bad title. I want to do the following in .NET 3.5:

void Invoke(Action callback)
{
   callback();
}

But I'm wondering if there's some already built-in classes which already have this functionality. For example, if I could do the following I would be happy (but I know I can't):

Action.Run(()=>{}}

I know there's a bunch of solutions to this problem, like writing my own helper class, or an extension. But as I said, I'm wondering if this is possible to do without any of that.

To clarify:

I want this solution because I have a method definition like this:

private void HelloWorld(Action callback)
{
#if DOTNET4.0+ //This code won't be compiled for DOTNET3.5
   Action.Run(async ()=>{
      await someTask;
      callback();
   });
#else //This code will be
   callback();
#endif
}

The reason I don't wanted to use Task.Run(...) Is because I wanted to minimize the amount of code dependent on .NET4.0+. If there's is no alternative to Task.Run(...), then I will go with it.

Upvotes: 0

Views: 91

Answers (1)

IS4
IS4

Reputation: 13187

Well, a void lambda with no arguments can be called like this:

((Action)(()=>{}))()

or

((Action)(()=>{})).Invoke()

You always have to assign a type to the lambda (even implicitly), before you are allowed to work with it.

Upvotes: 1

Related Questions