Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why must C# operator overloads be static?

Tags:

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?)

like image 750
dkackman Avatar asked Jan 07 '10 03:01

dkackman


People also ask

Why do we use C?

C is a general-purpose programming language and can efficiently work on enterprise applications, games, graphics, and applications requiring calculations, etc. C language has a rich library which provides a number of built-in functions. It also offers dynamic memory allocation.

Why is C a good language?

The programs that you write in C compile and execute much faster than those written in other languages. This is because it does not have garbage collection and other such additional processing overheads. Hence, the language is faster as compared to most other programming languages.

Should C be my first language?

While C is one of the more difficult languages to learn, it's still an excellent first language pick up because almost all programming languages are implemented in it. This means that once you learn C, it'll be simple to learn more languages like C++ and C#.

Is it still worth learning C?

Is Learning C Worth It? Learning C is worth it. It is hard to avoid C because it is used to write OS kernels, databases, compilers, and many other applications. Knowledge of C will be required to debug or improve them.


2 Answers

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.

like image 82
Igor Zevaka Avatar answered Oct 14 '22 00:10

Igor Zevaka


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).

like image 40
Sapph Avatar answered Oct 13 '22 23:10

Sapph