Pages

2012-03-23

DOTNET: Overloading operators


To implement operators in your classes, you simply define static methods to overload the operator you
want to use—for example, the following fragment shows the declaration of a method that implements
the addition operator (+) to be used when adding together two instances of the type myClass:

public static string operator +(myClass C1, myClass w2)

Notice that the result of our addition is a string—you can return any type you choose. You can also
define the behavior for when operators are applied on different types, such as the following, which
declares a method that overrides the operator for when an instance of myClass and an int are added
together:

public static myClass operator +(myClass C1, int i)

The following fragment allows us to use the operator like this:

myClass newMyClass = C1 + 7;

Note that the order of the arguments is important—the previous fragment defines the behavior for a
myClass + int operation, but not int + myClass (i.e., the same types, but with their order reversed). We would need to define another method to support both orderings.

You can override the following operators:
+, -, *, /, %, &, |, ^, <<, >>

No comments:

Post a Comment