X hits on this document

892 views

0 shares

0 downloads

0 comments

261 / 396

C# LANGUAGE SPECIFICATION

Like other members, operators declared in a base class are inherited by derived classes. Because operator declarations always require the class or struct in which the operator is declared to participate in the signature of the operator, it is not possible for an operator declared in a derived class to hide an operator declared in a base class. Thus, the new modifier is never required, and therefore never permitted, in an operator declaration.

Additional information on unary and binary operators can be found in §‎7.2.

Additional information on conversion operators can be found in §‎6.4.

10.9.1 Unary operators

The following rules apply to unary operator declarations, where T denotes the class or struct type that contains the operator declaration:

A unary +, -, !, or ~ operator must take a single parameter of type T and can return any type.

A unary ++ or -- operator must take a single parameter of type T and must return type T.

A unary true or false operator must take a single parameter of type T and must return type bool.

The signature of a unary operator consists of the operator token (+, -, !, ~, ++, --, true, or false) and the type of the single formal parameter. The return type is not part of a unary operator’s signature, nor is the name of the formal parameter.

The true and false unary operators require pair-wise declaration. A compile-time error occurs if a class declares one of these operators without also declaring the other. The true and false operators are described further in §‎7.11.2 and §‎7.16.

The following example shows an implementation and subsequent usage of operator ++ for an integer vector class:

public class IntVector { public IntVector(int length) {...}

public int Length {...}// read-only property

public int this[int index] {...}// read-write indexer

public static IntVector operator ++(IntVector iv) { IntVector temp = new IntVector(iv.Length); for (int i = 0; i < iv.Length; i++) temp[i] = iv[i] + 1; return temp; } }

class Test { static void Main() { IntVector iv1 = new IntVector(4);// vector of 4 x 0 IntVector iv2;

iv2 = iv1++;// iv2 contains 4 x 0, iv1 contains 4 x 1 iv2 = ++iv1;// iv2 contains 4 x 2, iv1 contains 4 x 2 } }

Note how the operator method returns the value produced by adding 1 to the operand, just like the  postfix increment and decrement operators (§‎7.5.9), and the prefix increment and decrement operators (§‎7.6.5). Unlike in C++, this method need not modify the value of its operand directly. In fact, modifying the operand value would violate the standard semantics of the postfix increment operator.

248Copyright Microsoft Corporation 1999-2003. All Rights Reserved.

Document info
Document views892
Page views892
Page last viewedTue Dec 06 14:15:17 UTC 2016
Pages396
Paragraphs9401
Words133190

Comments