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?)
+13
A:
Answered in excruciating detail here:
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.
Igor Zevaka
2010-01-07 04:00:57
gonna give the green check to @Sapph just cause you've got waaaay more rep :)
dkackman
2010-01-07 04:09:32
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
2010-01-07 04:12:02
+1 for excellent code snippet :D
Sapph
2010-01-07 07:18:29
A:
Perhaps its best to think why should the methods not be static. There is no need for state and hence this.
mP
2010-09-24 03:47:40