Search form

Here's a syntax idea I keep coming back to over and over again. I'm sure it's completely impractical for a well-established language like C# to introduce it at this point, but that doesn't stop me wondering about it. It's a little crazy, and all the use-cases can be accommodated with more traditional operators, so... you've been warned.

The idea is to introduce operators and and or which would be used like so:

The usefulness of such and and or constructs is maximized when it's combined with a long-ish expression that would otherwise have to be repeated or manually stored in a local.

Any bool-returning operator in C# could, in theory, be extended like this. It might be worth disallowing &&, || and ^ though, because (a && b or c or d) does not look all that natural. Moreover, it's already possible to write this concisely: a && (b || c || d).

The syntax proposed above looks particularly nice and natural for the == operator, but it's pretty weird if used with != (at least in English). Consider (foo != 5 and 7) – not very natural. Additionally, you're stuck with the one boolean operator, so while you can do "X greater than Y and Z", you cannot do "X greater than Y and less than Z".

So to address both of these issues, we could allow the operator to be specified separately for each value, like so:

if (SomeFunction(a, b, c) != 5 and != 6 and != 19) { ... }

This also enables concise range comparisons, for example:

if (SomeFunction(a, b, c) >= 5 and < 19) { ... }

and is nicely generalized, unlike, for example, the SQL between operator.

That's about it. I realise that this is just a sketch of an idea, nowhere near to a full-blown language proposal. I don't feel it's worth writing this out as a complete proposal because, as Eric Lippert has taught me through his writing, things like this have a much higher cost than one naively assumes, in terms of the exact specification (taking care of subtle corner-cases), implementation, full test coverage, documentation etc. Hence I don't expect that this feature can possibly make it into C# at this stage, since the benefits are relatively small.

On the upside, I don't have to think about all the tricky issues that such a feature will invariably involve. Here are just a few items that I didn't bother to think about. How exactly does the operator precedence work here? Can you combine and and or in the same expression and if so, can you use parentheses for grouping? Can you have the ands and ors on either side of the boolean operator, or only on the right? Do they short-circuit or not?

And last but not least, do you call them “operators” or do you come up with a new term?