Thursday 12 July 2012

Operator Overloading in C#

A feature from C++. Operands can be custom classes or structs. syntactically just a static method with keyword operator immediately preceding the operator to overload, then the operand params. Exs. +, -, ++, % (modulo), == etc.

Example from MSDN:
public static Complex operator+ (Complex c1, Complex c2)

If you are implementing your own collection classes, you may want to add support for subscripting into the collection. In this case, you cannot "overload" the subscript operator, but instead must create an INDEXER.

An indexer works as follows.

class MyCoolCollectionWithIndexerSupport<T>
{
   public T this[int i]
  {
    get { return _arr[i]; }
    set { _arr[i] = value; }
  }
}

(this is an interesting use of the this keyword. commonly this is used to refer to the current instance of a class, and as a qualifier for variables within a class. static member functions do not have a this pointer).

No comments: