about operator overloading

T

Tony Johansson

Hello!

When you are about to use and define operator overloading the method used
must be defined to be
static.
What is the reson for this?
Would it have been possible to have these methods as instance method
instead?


//Tony
 
M

Marc Gravell

Partly because that is how operators are defined in C#... they are
resolved via static analysis, not virtcall. One advantage of this is
that it allows you to pass nulls into either-side of a binary operator
(or null as the single arg to a unary operator) without it causing
issues (which is quite handy). Knowing which argument to base virtcall
on in a binary/ternary would be interesting...

Of course, there is nothing to stop you from having operator-esque
instance methods - the prime example being Equals (compare to the
== / != operators), but also look at things like the instance
DateTime.Add/Subtract methods (compare to the +/- operators).

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top