CHAPTER 22

image

Operator Overloading

Operator overloading allows operators to be redefined and used where one or both of the operands are of a certain class. When done correctly, this can simplify the code and make user-defined types as easy to use as the simple types.

Operator overloading example

In this example, there is a class called MyNum with an integer field and a constructor for setting that field. There is also a static Add method that adds two MyNum objects together and returns the result as a new MyNum object.

class MyNum{   public int val;  public MyNum(int i) { val = i; }    public static MyNum Add(MyNum a, MyNum b) {    return new MyNum(a.val ...

Get C# Quick Syntax Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.