I'm working on a method that will save checkstates to a SQL server and something occured to me and I thought I would ask if there is a simpler way of doing this.

If I have a single parameter, for example an initial checkstate, and an if...else statement is supposed to act on that parameter, is there a way to condense the if statement so I don't have to explicitly show all the possible "or" situations for that parameter?

An example might help. Here's what I have been doing forever which works:

When a parameter has more than 2 possible values (a checkstate has 3, checked, indeterminate and unchecked) I have been doing this for values that I consider equal for whatever reason:

                if (Location.InitialCheckState == CheckState.Checked || Location.InitialCheckState == CheckState.Indeterminate))
                {
                    //do stuff
                }
                else if (Location.InitialCheckState == CheckState.Unchecked)
                {
                    //do more stuff
                }

In the above code, checked and indeterminate should be treated the same, but instead of explicitly stating "Location.InitialCheckState == ..." twice, is it possible to do something like the following (the following code does not compile btw):

                if (Location.InitialCheckState == (CheckState.Checked || CheckState.Indeterminate))
                {
                    //do stuff
                }
                else if (Location.InitialCheckState == CheckState.Unchecked)
                {
                    //do more stuff
                }

I understand that I could use != in the first statement (ie Location.InitialCheckState != CheckState.Unchecked) but if there are multiple options (hundreds) using the != is just as bad.

I've browsed the MSDN articles and never found anything so I'm assuming it cannot be done and it just needs to be written out, but I thought I would ask.

Ideas? Suggestions?

You can use a switch statement like this:

switch (Location.InitialCheckState) {
        case CheckState.Checked:
        case CheckState.Indeterminate:
            // do stuff
            break;
        case CheckState.Unchecked:
            // do other stuff
            break;
        default:
            // Something is wrong here as it has to be one of the above
            throw new ArgumentException("Invalid value for Location.InitialCheckStat = " + Location.InitalCheckState.ToString());
            break;
    }

If you have more states, just continue to add them as needed.

Hmmm, thats a good point. I don't know why I never thought of that, but that's actually a good idea.

Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.