Subscribe

RSS Feed (xml)

C# Operator Overloading

Operator overloading is closely related to method overloading. To overload an operator, you use the operator keyword to define an operator method, which defines the action of the operator relative to its class.

There are two forms of operator methods: one for unary operators and one for binary operators. The general form for each is shown here:

// General form for overloading a unary operator.
public static ret-type operator op(param-type operand)
{
   // operations
}

// General form for overloading a binary operator.
public static ret-type operator op(param-type1 operand1, param-type1 operand2)
{
   // operations
}

Here, the operator that you are overloading, such as + or /, is substituted for op. The ret-type is the type of value returned by the specified operation. Although it can be of any type you choose, the return value is often of the same type as the class for which the operator is being overloaded. This correlation facilitates the use of the overloaded operator in expressions. For unary operators, the operand is passed in operand. For binary operators, the operands are passed in operand1 and operand2.

For unary operators, the operand must be of the same type as the class for which the operator is being defined. For binary operators, at least one of the operands must be of the same type as its class. Thus, you cannot overload any C# operators for objects that you have not created. For example, you can't redefine + for int or string.

One other point: Operator parameters must not use the ref or out modifier.

No comments:

Post a Comment

Archives

LocalsAdda.com-Variety In Web World

Fun Mail - Fun in the Mail