Search code examples
c#lambdacollection-initializer

Initializing a list of lambda expressions


I'm designing a state machine class and want to use lambda expressions to represent conditions to satisfy the state transition objects. When I create a new State Transition object, I also want to pass it a list of Conditions that it can use to evaluate whether or not to move to the next state. However, I'm having problems initializing the list of Conditions. Here is a sample, simplified code example that illustrates the problem I'm having:

// Alias for delegate function
using Condition = Func<int, bool>;

class SomeStateClass
{
    public void SomeFuncToCreateConditionList()
    {
        List<Condition> conditions = new List<Condition>({
            { new Condition(x => x > 5) },
            { new Condition(x => x > 5 * x) }
        });
    }
}

I'm getting a syntax error for the curley brace on the line List<Condition>({ saying ) expected, and another syntax error on the closing parenthesis saying

new Condition(
; expected
} expected

I'm sure there is something stupid i'm missing here but I've been staring at it too long and can't seem to spot it. Any thought?


Solution

  • You have a mistake in your List-initializer.

    It should be new List<Condition> { ... } instead of new List<Condition>({...}) You also don't need to wrap each new Condition() in braces.

    This should work:

    // Alias for delegate function
    using Condition = Func<int, bool>;
    
    class SomeStateClass
    {
        public void SomeFuncToCreateConditionList()
        {
            List<Condition> conditions = new List<Condition>
            {
                new Condition(x => x > 5),
                new Condition(x => x > 5 * x)
            };
        }
    }
    

    or, a shorter method:

    public void SomeFuncToCreateConditionList()
    {
        var conditions = new List<Condition>
        {
            x => x > 5,
            x => x > 5 * x
        };
    }