69

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.

Aaron Palmer
  • 8,912
  • 9
  • 48
  • 77
  • no language have This capability... – AminM Jul 05 '13 at 16:05
  • 16
    @JesonPark - Not true. F# has it as others have pointed out, and [C++ has it as well.](http://stackoverflow.com/questions/1515399/can-you-make-custom-operators-in-c) [CoffeeScript](http://coffeescript.org/) offers several new operators as syntactic sugar for JavaScript idioms, and it's so customizable that you could describe it as allowing custom operators. The last one's a bit tricky, since you'd technically be extending the language. – Justin Morgan - On strike Jul 24 '13 at 18:55
  • @JustinMorgan: as mentioned in CodeProject article _"C++ supports operator overloading, but you are not allowed to create your own operators"_ this is emulation!! – AminM Jul 24 '13 at 19:02
  • @JesonPark - I don't see the article you're talking about, but the [example](http://cogwheel.info/idop/) from Cogwheel's answer (on the SO question I linked to) results in code that works exactly like custom operators. Whether or not they're baked into the language, you can make them work. Either way, your statement (that no language has this capability) is invalid for F#. – Justin Morgan - On strike Jul 24 '13 at 20:00
  • @JesonPark In Scala it would be `implicit class (y: Int) { def (z: Int) = y min z }` -- the implicit class to add a method to `Int`, and then the method itself. _This_ particular method wouldn't work because `` is a xml-start keyword. – Daniel C. Sobral Mar 31 '14 at 16:01
  • @JustinMorgan I talk About [This Artical](http://www.codeproject.com/Articles/31783/Custom-User-Defined-Operators-in-C) – AminM Mar 31 '14 at 16:22
  • 1
    Even if it were possible, I still don't think it would be a good idea. It's much less readable than a method, e.g. `Min(y, z)`. – Thomas Levesque Jul 01 '14 at 08:32
  • Haskell has fully user-defined operators AFAIK. – user1982779 Jan 26 '16 at 20:25
  • [Overloadable Operators (C# Programming Guide)](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/overloadable-operators) – Sen Jacob Jul 14 '17 at 12:46
  • I'd also love to do this. What about an operator to assign `b` to `a` but only when `a` is already missing a value. eg `a ??= b;` Can't be done as elegantly with a method – userSteve Apr 20 '18 at 14:52
  • Ruby has some tricks that sorta allow you to do this: https://stackoverflow.com/questions/11874579/define-custom-ruby-operator – Reuel Ribeiro Jan 06 '19 at 15:50
  • 2
    @userSteve This has been proposed for C# 8 - [null coalescing assignment](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/null-coalescing-assignment) – phuzi Sep 12 '19 at 07:19
  • 1
    @AminM no literally there thousands of languages which offers better operator handling than c# – Ramsey Nov 16 '22 at 17:08
  • How about a Dot and Cross Product custom operator? I've seen people override the * operator for Dot, and that's not bad. I've seen the modulo (%) operator overridden for Cross Product since % "looks like a cross". That's horrible. It would be much more descriptive to be able to do "vec1 Dot vec2" or "vec1 Cross vec2". Yes, these could be functions, but mixing chaining functions and applying actual operators (like +, -, *) doesn't flow as nicely. I know there would need to be a way to define operator precedence too. This would probably never make it into C#. Just wishful thinking. :) – Lee Jan 29 '23 at 16:16
  • I had an interesting thought on this. It would be "syntactic sugar" (C# does that a lot), but if you had a method that took two arguments, you could call it by "Cross(a, b)" or "a Cross b". That would give you the syntax of using it like an operator. Maybe require it to have an OperatorPrecedenceAttribute that specifies what operators are lower/higher than it? Or in some way specify operator precedence... I'm sure there are holes in that proposal that I'm not thinking of. But it's an interesting idea. :) – Lee Jan 29 '23 at 16:22

7 Answers7

46

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

AgileJon
  • 53,070
  • 5
  • 41
  • 38
30

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

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

let (<?) = min
Aaron Franke
  • 3,268
  • 4
  • 31
  • 51
Dario
  • 48,658
  • 8
  • 97
  • 130
20

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 Z
  • 128,184
  • 27
  • 255
  • 279
10

I'm surprised no one mentioned "order of operations".

When the compiler evaluates an expression it has to be concerned with performing the operations in the correct order so that (1+2*3) = (2*3+1) multiplication always happens before addition at the same "level" in the expression.

When you override and operator, you can change what the operator does, but not the order in which the compiler will evaluate it. If you did created a new operator, there is no way to tell the compiler what order to evaluate it in relation to the others. So if you write x <? 2 + 5 Do you perform the x <? 2first then add 5 or do you perform the addition first and then do x <? 7.

Hari_pb
  • 7,088
  • 3
  • 45
  • 53
Jeff
  • 109
  • 1
  • 3
  • If this would get added to C# at any point, you would *probably* (as its not a thing "yet") just use Attributes like [OrderOfOperations.Dot] which would tell the compiler to make it have the same priority as dot operations (*, /, **) – GoldenretriverYT Jan 25 '23 at 11:59
7

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
  • 839
  • 2
  • 7
  • 15
  • 2
    Not if it's a known feature in another language like this question asks: http://stackoverflow.com/questions/523403/can-i-define-a-perl-like-binding-operator-in-c – Camilo Martin Nov 07 '10 at 12:25
  • 1
    Same can be said for any operator overloading – JNF Jul 05 '13 at 08:01
  • 9
    I disagree. I think operator overloading makes sense in many cases. For instance, if adding two instances of a type together makes sense, you might wish to overload the + operator instead of creating an .Add() method. Intuitively, someone sees "+" and they understand the operator is arithmetically adding the two things together. If that is what the overload is effectively doing, then it's easily understood. – Paul Hooper Jul 15 '13 at 19:35
  • 1
    I would like to use `====` so that my whole dev team knows that we are using a overridden test for that specific object. Thats all, but yea.. All i wanted to avoid is using methods in if's.. just messing around. – Piotr Kula Apr 29 '14 at 09:26
6

No, but you can create Extension Methods instead of this

y.MethodName(z)
Rony
  • 9,331
  • 2
  • 22
  • 22
-4

you can try to overload other operator like % or + to act as a <? operator.

Will be fun

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
Tiago Peczenyj
  • 4,387
  • 2
  • 22
  • 35