Is it possible to create a new operator in c#?

I know you can overload an existing operator. I want to know if it is possible to create a new operator. Here's my scenario.

I want this:

var x = (y < z) ? y : z;

To be equivalent to this:

var x = y <? z;

In other words, I would like to create my own <? operator.


Solution 1:

No, it is not possible. You would need to create a method instead

Solution 2:

No, but you can overload some existing operators in C#.

In some other languages, like F#, you can use:

let (<?) = min

Solution 3:

As the other answers have said, you can't create a new operator - at least, not without altering the lexer and parser that are built into the compiler. Basically, the compiler is built to recognize that an individual character like < or ?, or a pair like >> or <=, is an operator and to treat it specially; it knows that i<5 is an expression rather than a variable name, for instance. Recognizing an operator as an operator is a separate process from deciding what the operator actually does, and is much more tightly integrated into the compiler - which is why you can customize the latter but not the former.

For languages which have an open-source compiler (such as GCC) you could, theoretically, modify the compiler to recognize a new operator. But it wouldn't be particularly easy, and besides, everyone would need your custom compiler to use your code.