An operator is a symbol that causes C# to take an action.
The assignment operator (=
)
assigns a value to an object or variable.
C# includes four simple arithmetic operators: +
, -
,
*
, and /
, and numerous variations such as
+=
, which increments a variable
on the left side of the operator by the value on the right
side.
When you divide integers, C# discards any fractional remainder.
The modulus operator (%
)
returns the remainder from integer division.
C# includes numerous special operators such as the
self-increment (++
) and
self-decrement (—) operators.
To increment a value before assigning it, you use the prefix
operator (++x
); to increment the
value after assigning it, use the postfix operator (x++
).
The relational operators compare two values and return a Boolean. These operators are often used in conditional statements.
The conditional operator (?:
) is the one ternary operator found in
C#. It invokes the expression to the left of the colon if the tested
condition evaluates true, and the expression to the right of the
colon if the tested condition evaluates false.
The compiler evaluates operators according to a series of precedence rules, and parentheses have the “highest” precedence.
It is good programming practice to use parentheses to make your order of precedence explicit if there may be any ambiguity.