ermahgerd ermahgerd - 1 month ago 9
C# Question

Possible to combine two Actions in c#?

I'm just playing around with

Action
s to extract the lambda expressions.

I have a boolean variable, and based on it's value, my lambda body should be different.

However, in this particular case, the difference is just calling another method which doesn't change the return type. This is what I have:

Action<MyType> myLambda;

if (myBooleanCondition)
{
myLambda = x => x.ChangeBehavior();
}
else
{
myLambda = x => x.ChangeBehavior().ChangeSize();
}


Is it possible to reduce/merge the two lambda definitions to one to make it more elegant?

This project uses C# 4.0, but if it's been simplified in the newer versions, please let me know.

Answer

It's possible to use the += operator to concatenate delegates, which you can use to simplify your specific example.

For example, you could simplify your code like this:

Action<MyType> myLambda = x => x.ChangeBehavior();

if (!myBooleanCondition)
    myLambda += x => x.ChangeSize();

Full compilable example:

using System;

namespace Demo
{
    class MyType
    {
        public MyType ChangeBehavior()
        {
            Console.WriteLine("ChangeBehavior()");
            return this;
        }

        public void ChangeSize()
        {
            Console.WriteLine("ChangeSize()");
        }
    }

    class Program
    {
        static void Main()
        {
            var x = new MyType();

            test(true)(x);       // Calls ChangeBehavior()
            Console.WriteLine();
            test(false)(x);      // Calls ChangeBehavior() and then ChangeSize()
        }

        static Action<MyType> test(bool myBooleanCondition)
        {
            Action<MyType> myLambda = x => x.ChangeBehavior();

            if (!myBooleanCondition)
                myLambda += x => x.ChangeSize();

            return myLambda;
        }
    }
}

Having said that, I don't think you should do it - it's too subtle. There's nothing wrong with your original code!

Comments