Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

operators

c#

I may not be using the right word here and that could be why I can't find the answer on my own. I have a + & - operator in my class, but I want to add a negative operator... I basicly what to be able to do this:

myMethod(myClass, -myClass);

If you need code examples to help me out let me know, but I think this should be pretty strait forward... Or that it can't be done.

like image 641
Anthony Nichols Avatar asked Feb 11 '13 17:02

Anthony Nichols


People also ask

How to add two class objects using operator + in C++?

Now, if the user wants to make the operator “+” to add two class objects, the user has to redefine the meaning of “+” operator such that it adds two class objects. This is done by using the concept “Operator overloading”. So the main idea behind “Operator overloading” is to use c++ operators with class variables or class objects.

What is the addition operator in C++?

Here, ‘+’ is the operator known as addition operator and ‘a’ and ‘b’ are operands. The addition operator tells the compiler to add both of the operands ‘a’ and ‘b’. C/C++ has many built-in operator types and they are classified as follows:

Which operator will assign the value of a + B to C?

C = A + B will assign the value of A + B to C. +=. Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand.

How do you make a negative integer in C?

In the C language, you have several ways to create a negative integer: You can assign a negative value to a variable, you can perform math that results in a negative value, or you can manipulate bits to convert a positive value to a negative one. That final operation isn’t as easy as it sounds.


1 Answers

Sure, the unary - operator is overloadable:

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

Be careful not to abuse these features as consumers may be unaware of the semantics of these operators - unlike methods (which can be well-named), it is often not immediately obvious what a custom operator on a type does. Hopefully, your class represents a vector of some sort or similar?

like image 170
Ani Avatar answered Oct 29 '22 18:10

Ani