Why does C# require operator overloads to be static methods rather than member functions (like C++)? (Perhaps more specifically: what was the design motivation for this decision?)
Asked
Active
Viewed 1.3k times
25

Rob Kennedy
- 161,384
- 21
- 275
- 467

dkackman
- 15,179
- 13
- 69
- 123
-
1C++ allows operators to be free (ie. non member) functions. But C# decided to put a Stalinian ban on free functions, so you have to put static there. – Alexandre C. Aug 29 '11 at 19:36
3 Answers
36
This has been answered in excruciating detail by Eric Lippert in a blog post that has since been removed. Here is the archived version.
There is also another subtler point about value types and instance operators. Static operators make this kind of code possible:
class Blah {
int m_iVal;
public static Blah operator+ (Blah l, int intVal)
{
if(l == null)
l = new Blah();
l.m_iVal += intVal;
return l;
}
}
//main
Blah b = null;
b = b + 5;
So you can invoke the operator, even though the reference is null. This wouldn't be the case for instance operators.

Glorfindel
- 21,988
- 13
- 81
- 109

Igor Zevaka
- 74,528
- 26
- 112
- 128
-
1gonna give the green check to @Sapph just cause you've got waaaay more rep :) – dkackman Jan 07 '10 at 04:09
-
lol i saw the rep go up and then down for like a second. Well deserved, Sapph put more effort into the answer. – Igor Zevaka Jan 07 '10 at 04:12
-
2IMHO, don't do this. Looks like a bad design, because this behavior seems to be unexpected. – LOST Mar 04 '19 at 19:44
28
Take a look at this post.
A couple of reasons, the primary seeming to be to preserve operator symmetry (such that the left hand side of a binary operation does not get special treatment, as being responsible for dispatching the operation).

Sapph
- 6,118
- 1
- 29
- 32
-
1@Frederic Here you go https://web.archive.org/web/20150906063729/http://blogs.msdn.com/b/ericlippert/archive/2007/05/14/why-are-overloaded-operators-always-static-in-c.aspx – Rain May 04 '20 at 10:35
0
Perhaps its best to think why should the methods not be static. There is no need for state and hence this.

mP.
- 18,002
- 10
- 71
- 105
-
There might not be a state benefit but having virtual operator overloading would be cool. The state-thing is not the reason why it is not available in C#. – Noel Widmer Mar 17 '17 at 20:56