Operator overloading is all about providing customized operation for an operator in a class or struct without destroying the original functionality. For example, ++ is a unary operator to increase number by one. But the same unary operator can be defined in Page class to increase the page number. This is required when number in a read-only field or property in Page class.
Only a fixed set of operators can be overloaded in C#. Other operators cannot be overloaded. You cannot invent new operator symbols for operator overloading. The compiler only recognizes a fixed set of operator symbols.
Operator overloading in C# means providing implementation for an existing operator, not creating a new operator syntax.
In C#, operator-overloading methods have strict rules.
- The operator-overloading methods must be public.
- The operator-overloading methods must be static. Reason: Operator overloads belong to the type, not to an individual object instance.
- The operator-overloading method must return a non-void type value.
- In C#, the number of parameters in an overloaded operator is fixed by the operator category. For unary and binary operators, the number of parameters is one and two respectively.
- Operator overload must be declared in a class/struct, and at least one operand must be that class/struct.
public static ReturnType operator OperatorSymbol(Type arg1, ...)
{
// implementation
}
Example
class Page
{
public int Number { get; }
public Page(int number)
{
Number = number;
}
public static Page operator ++(Page page)
{
return new Page(page.Number + 1);
}
}
class ClientClass
{
static void Main(string[] args)
{
Page p = new Page(10);
p++;
Console.WriteLine(p.Number); // 11
}
}
Note that read-only state (or immutable objects) is one situation where operator overloading can become useful. The deeper idea is not only “read-only property”; it is encapsulation of state transitions.
Immutable/read-only objects are one common scenario where operator overloading becomes more valuable. But the main reason is preserving the class’s own behavior and invariants, not merely making a property read-only.
Special Remarks
- The return type does not always have to be the containing type.
- For binary operator, out of two parameters, one can must be of the type of containing class/struct and other can be any other type.
class Taxation
{
public int Tax { get; set; }
}
class Sales
{
public int Amount { get; set; }
public Sales(int amount)
{
Amount = amount;
}
public static Sales operator +(Sales a, Taxation b)
{
return new Sales(a.Amount + b.Tax);
}
}
class Program
{
static void Main()
{
Sales d = new Sales(1000);
Taxation c = new Taxation { Tax = 50 };
Sales result = d + c;
Console.WriteLine(d.Amount); // 1000
Console.WriteLine(result.Amount); // 1050
}
}
The return type does not always have to be the containing type.public static bool operator >(DemoClass a, DemoClass b)
{
return true;
}
No comments:
Post a Comment