OR (|), XOR (^), AND (&) overload

How to reload &, | and ^ operators in C # and how does overload work?

I tried to find good answers for some time, but did not find. I will talk about any useful articles.

0
source share
3 answers

By implementing operators for your classes in C #, you are not actually overloading operators. You just implement them for the first time. These methods, like any other, but with special syntax. Instead of calling c = Add(a, b) you call c = a + b , where + is the operator (method) that returns the value.

By implementing the following methods, the &= |= and ^= methods were automatically implemented.

 public class MyClass { public static MyClass operator &(MyClass left, MyClass right) { return new MyClass(); } public static MyClass operator |(MyClass left, MyClass right) { return new MyClass(); } public static MyClass operator ^(MyClass left, MyClass right) { return new MyClass(); } } var a = new MyClass(); var b = new MyClass(); var c = a & b; var d = a | b; var e = a ^ b; a &= b; // a = a & b; c |= d; // c = c & d; e ^= e; // e = e ^ e; 

Overloading is performed at compile time. This ensures that a particular method will be called based on the method name, type of parameter and quantity.

Overiding is performed at runtime. It allows you to call a subclass method instead of the parent method, even if the instance was considered as the parent class.

+1
source

In some articles / tutorials / links to operator overloading, including binary / bitwise operators and sample source code, see:

As for "how to use them," the basic rule is that overloaded operators should make sense in the domain that you implement for them ...

For example, you could build a genetic / evolutionary algorithm and define some / all bitwise / binary operators according to the “recombination / mutation” step (that is, creating the next generation from the current population) of this algorithm - this would create quite elegant code in this particular context.

+3
source

How to use them? Carefully. They should make sense. For example. The definition says that the type for storing ComplexNumber or Matrix and then overloading arithmetic operators makes sense.

Do not go down the stupid path of operator overloading because you don't like typing.

eg. MyThingyList + SomeFileName loads MyThingyList from a file.

or

MyThingyList-- calls MyThingsList.Clear ().

0
source

All Articles