8.18. Operator Overloading

We have mentioned that certain operators can be overloaded and certain other operators cannot be overloaded. Overloading an operator means to customize its behavior depending on the context in which it is being used. For example, the additive (+) operator is used for adding numerical values when used in the numeric context (that is, both operands are numeric data types). However, when one or more operands of this operator are strings, the operation is treated as string concatenation. You can say that the + operator is overloaded for strings to concatenate them.

Overloading operators makes sense if the context in which they are used is intuitive to the end user. For example, strings do not overload the multiplicative * operator because it does not make sense to multiply two strings. Operator overloading is a powerful tool that can be used to write terse, intuitive code.

Before we look at an example of operator overloading, it's worth noting some facts about C#'s operator overloading:

  • Overloadable unary operators are +, -, !, ~, ++, ==, true, and false.

  • Overloadable binary operators are +, -, *, /, %, &, |, ^, <<, >>, ==, !=, >, <, >=, and <=.

  • It is not possible to overload member access, method invocation, or the =, &&, ||, ?:, checked, unchecked, new, typeof, as, and is operators.

  • When a binary operator is overloaded, the corresponding assignment operator (if any) is also implicitly overloaded. For example, an overload of operator + is also an overload of operator +=.

  • Cast operations, such as (T)x, are overloaded.

  • Element access, such as a[x], is not considered an overloadable operator. Instead, user-defined indexing is supported through indexers.

  • A user-defined operator cannot have the same signature as a predefined operator.

  • User-defined operator declarations cannot modify the syntax, precedence, or associativity of an operator. For example, the * operator is always a binary operator and is always left-associative.

  • When applying operators, the CLR checks to see whether there is a custom overload of the operator. If one is defined, the CLR uses that; otherwise, it uses the default implementation of the operator.

Listing 8.15 shows a simple ComplexNumber class with the +, -, *, <, and > operators overloaded.

Listing 8.15. Operator Overloading (C#)
using System;

class ComplexNumber {

  private float real;
  private float imaginary;
  public ComplexNumber(float real, float imaginary) {
    this.real = real;
    this.imaginary = imaginary;
  }

  public float Real {
    get {
      return real;
    }
  }
  public float Imaginary {
    get {
      return imaginary ;
    }
  }

  public static ComplexNumber operator +(ComplexNumber c1,
                                      ComplexNumber c2) {
    return new ComplexNumber((c1.Real + c2.Real),(c1.Imaginary
                        + c2.Imaginary) );
  }
  public static ComplexNumber operator - (ComplexNumber c1,
    ComplexNumber c2) {
    return new ComplexNumber((c1.Real - c2.Real),
                             (c1.Imaginary - c2.Imaginary) );
  }
  public override string ToString() {
    return real + " + " + imaginary + "i";
  }

  public static void Main() {
    ComplexNumber num1 = new ComplexNumber(1.2f, 23.45f);
    Console.WriteLine("Complex Number #1: " + num1);
    ComplexNumber num2 = new ComplexNumber(2.4f, 46.57f);
    Console.WriteLine("Complex Number #2: " + num2);
    Console.WriteLine("Adding Complex Number (#1 + #2): " + 
                                (num1 + num2));
    Console.WriteLine("Subtracting Complex Number (#1 - #2): "
                                + (num1 - num2));
  }
}

The output of Listing 8.15 is as follows:

Complex Number #1: 1.2 + 23.45i
Complex Number #2: 2.4 + 46.57i
Adding Complex Number (#1 + #2): 3.6 + 70.02i
Subtracting Complex Number (#1 - #2): -1.2 + -23.12i

Note that the methods that define the operator are static in nature, but the operator usage is on the instance of the ComplexNumber class. Again, you can implement whatever you want with your operators, but it is a bad idea to overload operators in a manner that is not intuitive to the end user.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.222.185