C# Tutorial Lesson 8: Operators

C# has a number of standard operators, taken from C, C++ and Java. Most of these should be quite familiar to programmers; the less common ones are covered elsewhere.

The diagram below lists the standard operators. Note that when writing classes it is possible to change the default behaviour of some of these operators (ie to 'overload' the operator), although this should only be done where the resultant semantics makes sense. The diagram indicates which of the operators are overloadable.

CategoryNameSyntax ExampleOverloadable?
 Struct pointer member accessA->BNo
 Method callf(x)No
 Post incrementc++Yes
 Post decrementc--Yes
 Constructor callc = new Coord();No
 Array stack allocationint* c = stackalloc int[10]No
 Struct size retrievalsizeof (int)No
 Arithmetic check onchecked {byte c = (byte) d;}No
 Arithmetic check offunchecked {byte c = (byte) d;}No
UnaryPositive value+10Yes
 Negative value-10Yes
 Bitwise complement~(int x)Yes
 Pre increment++cYes
 Pre decrement--cYes
 Type cast(myType)cNo
 Value at addressint* c = d;No
 Address value ofint* c = &d;No
Type operatorsType equality / compatibilitya is StringNo
 Type retrievaltypeof (int)No
 Shift bits rightc>>3Yes
 Shift bits leftc<<3Yes
Relational and LogicalLess thanc<dYes
 Greater thanc>dYes
 Less than or equal toc<=dYes
 Greater than or equal toc>=dYes
 Bitwise andc&dYes
 Bitwise orc|dYes
 Logical andc&&dNo
 Logical orc||dNo
 Conditionalint c=(d<10) ? 5:15No

Overloading operators

To overload an operator in a class, one defines a method using the 'operator' keyword. For instance, the following code overloads the equality operator (see lesson 13 for details about methods).

public static bool operator == (Value a, Value b)
{return a.Int == b.Int}

Where an operator is one of a logical pair, both operators should be overwritten if any one is. These pairs are the following:

== and !=
< and >
<= and >=

Link Building Information