Add a negative operator (?) To a class in C #

I cannot use the correct word here, and therefore I cannot find the answer on my own. I have a + and - operator in my class, but I want to add a negative operator ... I basically can do this:

myMethod(myClass, -myClass);

If you need some code examples to help me, let me know, but I think it should be quite difficult ... Or that it is not possible.

+8
operators c #
source share
2 answers

Of course, the unary operator - overloaded :

 public static MyClass operator -(MyClass myClass) { ... } 

Be careful not to overuse these functions, because consumers may not know the semantics of these operators — unlike methods (which can be well named), it is often not immediately clear what the user operator does in the type. Hope your class represents some kind of vector or similar?

+23
source share
 public static YourClass operator -(YourClass value) { } 
+4
source share

All Articles