tags:

views:

505

answers:

5

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.

+9  A: 

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

AgileJon
+8  A: 

No - You can just overload existing operators - See this

In languages like F#, you can:

let (<?) = max
Dario
sweet, I really need to look into F#.
Aaron Palmer
+3  A: 

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.

David Zaslavsky
+1 for explaining why; I was just about to do that. :)
Randolpho
+4  A: 

Not only can you not do that, but why would you want to?

I'm not sure what type your y and z are, but if they are of a numeric value type, you could probably use:

var x = Math.Min(y, z);

Though personally, I would still prefer:

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

But I'm a bit of a ? : junky.

Good code is not just tight and efficient, but also readable. Even if you are the only one ever reading it, you'd come back to that <? operator one day and wonder what the heck that did.

Paul Hooper
A: 

No, but you can create Extension Methods instead of this

y.MethodName(z)
Rony
2.GetMin(1) is weird
Dario