C Sharp Operators and Expressions
Previous | Table of Contents | Next |
C# Variables and Constants | C# Flow Control with if and else |
Purchase and download the full PDF and ePub versions of this Visual C# eBook for only $9.99 |
In C# Variables and Constants we looked at using variables and constants in C# and also described the different variable and constant types. Being able to create constants and variables is only part of the story however. The next step is to learn how to use these variables and constants in C# code. The primary method for working with the data stored in constants and variables is in the form of expressions. In this chapter we will look in detail at C# expressions and operators.
What is an Expression?
The most basic expression consists of an operator, two operands and an assignment. The following is an example of an expression:
int theResult = 1 + 2;
In the above example the (+) operator is used to add two operands (1 and 2) together. The assignment operator (=) subsequently assigns the result of the addition to an integer variable named theResult. The operands could just have easily been variables or constants (or a mixture of each) instead of the actual numerical values used in the example.
In the remainder of this chapter we will look at the various types of operators available in C#.
The Basic Assignment Operator
We have already looked at the most basic of assignment operators, the = operator. This assignment operator simply assigns the result of an expression to a variable. In essence the = assignment operator takes two operands. The left hand operand is the variable to which a value is to be assigned and the right hand operand is the value to be assigned. The right hand operand is, more often than not, an expression which performs some type of arithmetic or logical evaluation. The following examples are all valid uses of the assignment operator:
x = 10; // Assigns the value 10 to a variable named x x = y + z; // Assigns the result of variable y added to variable z to variable x x = y; // Assigns the value of variable y to variable x
Assignment operators may also be chained to assign the same value to multiple variables. For example, the following code example assigns the value 20 to the x, y and z variables:
int x, y, z; x = y = z = 20;
C# Arithmetic Operators
C# provides a range of operators for the purpose of creating mathematical expressions. These operators primarily fall into the category of binary operators in that they take two operands. The exception is the unary negative operator (-) which serves to indicate that a value is negative rather than positive. This contrasts with the subtraction operator (-) which takes two operands (i.e. one value to be subtracted from another). For example:
int x = -10; // Unary - operator used to assign -10 to a variable named x x = y - z; // Subtraction operator. Subtracts z from y
Operator | Description |
---|---|
-(unary) | Negates the value of a variable or expression |
* | Multiplication |
/ | Division |
+ | Addition |
- | Subtraction |
% | Modulo |
Note that multiple operators may be used in a single expression.
For example:
x = y * 10 + z - 5 / 4;
Whilst the above code is perfectly valid it is important to be aware that C# does not evaluate the expression from left to right or right to left, but rather in an order specified by the precedence of the various operators. Operator precedence is an important topic to understand since it impacts the result of a calculation and will be covered in detail the next section.
C# Operator Precedence
When humans evaluate expressions, they usually do so starting at the left of the expression and working towards the right. For example, working from left to right we get a result of 300 from the following expression:
10 + 20 * 10 = 300
This is because we, as humans, add 10 to 20, resulting in 30 and then multiply that by 10 to arrive at 300. Ask C# to perform the same calculation and you get a very different answer:
int x; x = 10 + 20 * 10; System.Console.WriteLine (x)
The above code, when compiled and executed, will output the result 210.
This is a direct result of operator precedence. C# has a set of rules that tell it in which order operators should be evaluated in an expression. Clearly, C# considers the multiplication operator (*) to be of a higher precedence than the addition (+) operator.
Fortunately the precedence built into C# can be overridden by surrounding the lower priority section of an expression with parentheses. For example:
int x; x = (10 + 20) * 10; System.Console.WriteLine (x)
In the above example, the expression fragment enclosed in parentheses is evaluated before the higher precedence multiplication resulting in a value of 300.
The following table outlines the C# operator precedence order from highest precedence to lowest:
Precedence | Operators |
---|---|
Highest | + - ! ~ ++x --x (T)x |
* / % | |
+ - | |
<< >> | |
< > <= >= is as | |
== != | |
& | |
^ | |
| | |
&& | |
|| | |
:? | |
Lowest | = *= /= %= += -= <<= >>= &= ^= |= |
It should come as no surprise that the assignment operators have the lowest precedence since you would not want to assign the result of an expression until that expression had been fully evaluated. Don't worry about memorizing the above table. Most programmers simply use parentheses to ensure that their expressions are evaluated in the desired order.
Compound Assignment Operators
C# provides a number of operators designed to combine an assignment with a mathematical or logical operation. These are primarily of use when performing an evaluation where the result is to be stored in one of the operands. For example, one might write an expression as follows:
x = x + y;
The above expression adds the value contained in variable x to the value contained in variable y and stores the result in variable x. This can be simplified using the addition compound assignment operator:
x += y
The above expression performs exactly the same task as x = x + y but saves the programmer some typing. This is yet another feature that C# has inherited from the C programming language.
Numerous compound assignment operators are available in C#. The most frequently used are outlined in the following table:
Operator | Description |
---|---|
x += y | Add x to y and place result in x |
x -= y | Subtract y from x and place result in x |
x *= y | Multiply x by y and place result in x |
x /= y | Divide x by y and place result in x |
x %= y | Perform Modulo on x and y and place result in x |
x &= y | Assign to x the result of logical AND operation on x and y |
x |= y | Assign to x the result of logical OR operation on x and y |
x ^= y | Assign to x the result of logical Exclusive OR on x and y |
Increment and Decrement Operators
Another useful shortcut can be achieved using the C# increment and decrement operators. As with the compound assignment operators described in the previous section, consider the following C# code fragment:
x = x + 1; // Increase value of variable x by 1 x = x - 1; // Decrease value of variable y by 1
These expressions increment and decrement the value of x by 1. Instead of using this approach it is quicker to use the ++ and -- operators. The following examples perform exactly the same tasks as the examples above:
x++; Increment x by 1 x--; Decrement x by 1
These operators can be placed either before or after the variable name. If the operator is placed before the variable name the increment or decrement is performed before any other operations are performed on the variable. For example, in the following example, x is incremented before it is assigned to y, leaving y with a value of 10:
int x = 9; int y; y = ++x;
In the following example, the value of x (9) is assigned to variable y before the decrement is performed. After the expression is evaluated the value of y will be 9 and the value of x will be 8.
int x = 9; int y; y = x--;
Comparison Operators
In addition to mathematical and assignment operators, C# also includes set of logical operators useful for performing comparisons. These operators all return a Boolean (bool) true or false result depending on the result of the comparison. These operators are binary in that they work with two operands.
Comparison operators are most frequently used in constructing program flow control. For example an if statement may be constructed based on whether one value matches another:
if (x == y) System.Console.WriteLine ("x is equal to y");
The result of a comparison may also be stored in a bool variable. For example, the following code will result in a true value being stored in the variable result:
bool result; int x = 10; int y = 20; result = x < y;
Clearly 10 is less than 20, resulting in a true evaluation of the x < y expression. The following table lists the full set of C# comparison operators:
Operator | Description |
---|---|
x == y | Returns true if x is equal to y |
x > y | Returns true if x is greater than y |
x >= y | Returns true if x is greater than or equal to y |
x < y | Returns true if x is less than y |
x <= y | Returns true if x is less than or equal to y |
x != y | Returns true if x is not equal to y |
Boolean Logical Operators
Another set of operators which return boolean true and false values are the C# boolean logical operators. These operators both return boolean results and take boolean values as operands. The key operators are NOT (!), AND (&&), OR (||) and XOR (^).
The NOT (!) operator simply inverts the current value of a boolean variable, or the result of an expression. For example, if a variable named flag is currently true, prefixing the variable with a '!' character will invert the value to be false:
bool flag = true; //variable is true bool secondFlag; secondFlag = !flag; // secondFlag set to false
The OR (||) operator returns true if one of its two operands evaluates to true, otherwise it returns false. For example, the following example evaluates to true because at least one of the expressions either side of the OR operator is true:
if ((10 < 20) || (20 < 10)) System.Console.WriteLine("Expression is true");
The AND (&&) operator returns true only if both operands evaluate to be true. The following example will return false because only one of the two operand expressions evaluates to true:
if ((10 < 20) && (20 < 10)) System.Console.WriteLine("Expression is true");
The XOR (^) operator returns true if one and only one of the two operands evaluates to true. For example, the following example will return true since only one operator evaluates to be true:
if ((10 < 20) ^ (20 < 10)) System.Console.WriteLine("Expression is true");
If both operands evaluated to be true, or both were false the expression with return false.
The Ternary Operator
C# uses something called a ternary operator to provide a shortcut way of making decisions. The syntax of the ternary operator is as follows:
[condition] ? [true expression] : [false expression]
The way this works is that [condition] is replaced with an expression that will return either true or false. If the result is true then the expression that replaces the [true expression] is evaluated. Conversely, if the result was false then the [false expression] is evaluated. Let's see this in action:
int x = 10; int y = 20; System.Console.WriteLine( x > y ? x : y );
The above code example will evaluate whether x is greater than y. Clearly this will evaluate to false resulting in y being returned to the WriteLine method for display to the user.
Purchase and download the full PDF and ePub versions of this Visual C# eBook for only $9.99 |
Previous | Table of Contents | Next |
C# Variables and Constants | C# Flow Control with if and else |