Leon Marzahn
Leon Marzahn

Reputation: 349

C# .NET Take Action as parameter for method that provides a function that can be executed from lambda instantiating this Action

to make it simpler what I just wrote basically means I want something like this:

var someClass = new someClass((func1, func2) =>
{
  if (cool)
  {
    func1(cool);
  }
  else
  {
    func2(cool);
  }
}

Is this possible? I tried with an Action but that didn't work. I would really appreciate some help :D

Upvotes: 0

Views: 71

Answers (3)

Boric
Boric

Reputation: 872

You can create a method that takes Action parameters and returns one of them based on some criteria, so that the return Action can then be executed at the callsite.

Action method (Action a, Action b)
{
    if (cool)
    {
        return a;
    }
    else
    {
        return b;
    }
}

Upvotes: 0

FractalCode
FractalCode

Reputation: 380

Ok, I hope this is what you are looking for:

  public class SomeClass
{
    public SomeClass(Action<Action<bool>, Action<bool>> func)
    {
    func(
            (i) =>{
                Func1(i);
            },

            (j) =>
            {
                Func2(j);
            });


    }

    public void Func1(bool cool)
    {

    }

    public void Func2(bool cool)
    {

    }

    public static void Main()
    {
        var someClass = new SomeClass((func1, func2) =>
          {
              var cool = true;
              if (cool)
              {
                  func1(cool);
              }
              else
              {
                  func2(cool);
              }
          });
    }
}

Upvotes: 1

Paul Swetz
Paul Swetz

Reputation: 2254

 var f = new Func<int>(() => { return 1; });
 var result = f.Invoke();

Is that what you are after?

syntax with input and output is

var myfunction = new Func((x,y,z) => { return a;});

var a = x.Invoke(x,y,z);

From edit comment

 public class someclass
 {
      private Func A = ......
      private Func B = ......
      public void somemethod(type x)
      {
           if(x) this.A.Invoke();
           else this.B.Invoke();  
      }
 }

Upvotes: 0

Related Questions