Expressions and Operators
An expression essentially denotes a value. The simplest kinds of
expressions are constants (such as 123
)
and variables (such as x
). Expressions
can be transformed and combined using operators. An operator takes one or more input
operands to output a new expression:
12 * 30 // * is an operator; 12 and 30 are operands.
Complex expressions can be built because an operand may itself be an
expression, such as the operand (12 *
30)
in the following example:
1 + (12 * 30)
Operators in C# are classed as unary, binary, or ternary—depending on the number of operands they work on (one, two, or three). The binary operators always use infix notation, where the operator is placed between the two operands.
Operators that are intrinsic to the basic plumbing of the language are called primary; an example is the method call operator. An expression that has no value is called a void expression:
Console.WriteLine (1)
Since a void expression has no value, it cannot be used as an operand to build more complex expressions:
1 + Console.WriteLine (1) // Compile-time error
Assignment Expressions
An assignment expression uses the =
operator to assign
the result of another expression to a variable. For example:
x = x * 5
An assignment expression is not a void expression. It actually
carries the assignment value, and so can be incorporated into another
expression. In the following example, the expression assigns 2 to
x
and 10 to y
:
y = 5 * (x = 2)
This style of expression can be used to initialize ...
Get C# 4.0 Pocket Reference, 3rd Edition 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.