0

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?

2 Answers 2

5

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
    };
}
Sign up to request clarification or add additional context in comments.

3 Comments

ReSharper tells that var conditions = new List<Condition> {x => x > 5, x => x > 5 * x}; would be the shortest form.
Or also new List<Condition>() { ... }.
Thanks for the quick response! Works great and looks much simpler than my previous approach :-).
1

Try this

new List<Condition> { ... }

or

new List<Condition>() { ... }

or if for some reason you want to use the syntax of the constructor

new List<Condition>(new[] { ... })

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.