Expressions and Operators

An expression is a sequence of operators and operands that specifies a computation. C# has unary operators, binary operators, and one ternary operator. Complex expressions can be built because an operand may itself be an expression, such as the operand (1 + 2) shown in the following example:

((1 + 2) / 3)

Operator Precedence

When an expression contains multiple operators, the precedence of the operators controls the order in which the individual operators are evaluated. When the operators are of the same precedence, their associativity determines the order. Binary operators (except for assignment operators) are left-associative; i.e., they are evaluated from left to right. The assignment operators, unary operators, and the conditional operator are right-associative; i.e., they are evaluated from right to left.

For example:

1 + 2 + 3 * 4

is evaluated as:

((1 + 2) + (3 * 4))

because * has a higher precedence that +, and + is a binary operator that is left-associative. You can insert parentheses to change the default order of evaluation. C# overloads operators, which means the same operator, or has different meanings for different types.

The following table lists C#’s operators in order of precedence. Operators in the same box have the same precedence, and operators in italic may be overloaded for custom types.

Table 2-2. Operator Precedence Table

Category

Operators

Primary

Grouping: (x)

Member access: x.y

Struct pointer member access: ->

Method call: f(x)

Get C# in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.