!= operator syntax for switch statements. (does not equal operator)

I’m trying to figure out the correct syntax for the != operator for switch statements. Ideally, it would look something like this:

    public enum Foo { A, B, C };
    public Foo foo;
    void Bar()
    {
        switch (foo)
        {
            case !Foo.A:
                DoStuff();
                break;
        }
    }

Just a not equals would not make much sense for a switch statement as this case would catch any other case. So you could only have two cases anyways, namely foo IS “Foo.A” or foo IS NOT “Foo.A”. No other cases would be possible. So it would be much easier to just use an if statement.

Our Captain is right that with the newer C# support we now have pattern matching magic for switch statements which can do all sorts of extra conditions. However I really don’t see any sensible reason for it here.

void Bar()
{
    if (foo != Foo.A)
        DoStuff();
}

This would do.

Just to make my point clear: A switch statement will always ever only hit one case only. So it’s not possible to have several cases which all are true. A switch can only execute a single case. The same is true for the new switch statements.

There’s a video that gives a good overview how pattern matching has evolved in C# and which features are available in which version of C#. Though as I said, even when you use guard cases there can only be a single case being hit. So the case that foo is not Foo.A it already covers all other cases.

There are ways to add more complex statements to switches. See the microsoft reference for switch-case in the section Case Guard.

In your case this could be done like this:

 switch(foo)
    {
        case var _ when foo != Foo.A:
            DoStuff();
            break;
    }

(See this link for source on stackoverflow)

I personally would just go back to if/elseif i think.