0

I have this code and it's work correctly,

    private void button1_Click(object sender, EventArgs e)
    {
        var func = new Action<int, int>((a, b) =>
        {
            var sum = a + b;
            MessageBox.Show(sum.ToString());
            //How can I return sum?
        });

        //var result=func(2,3);
        func(2, 3);
    }

How I can change func to return sum variable, I want use function as:

   var result=func(2,3);
3
  • Can u explain the relation of your subject and your question?! Commented Mar 8, 2014 at 19:39
  • 1
    Sounds like you want Func<int, int, int> which you can return a+b from Commented Mar 8, 2014 at 19:40
  • @Charleh sorry for wrong title, if you vote down me please vote me up. Commented Mar 8, 2014 at 19:53

1 Answer 1

4

An Action represents a method which does not return a value.

If you want to return a value you need to use a Func<TResult> which encapsulates a method that returns a value of the type specified by the TResult parameter.

So in your case you need a Func<T1, T2, TResult> where the arguments are int and so does the return type:

var func = new Func<int, int, int>((a, b) =>
{
    var sum = a + b;
    MessageBox.Show(sum.ToString());
    return sum;
});

var result=func(2,3);
Sign up to request clarification or add additional context in comments.

1 Comment

Not related to the question, but you don't need the new syntax when you create a delegate from a lambda, so either Func<int, int, int> func = (a, b) => { var sum = a + b; MessageBox.Show(sum.ToString()); return sum; }; or var func = (Func<int, int, int>)((a, b) => { var sum = a + b; MessageBox.Show(sum.ToString()); return sum; }); will give the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.