Operating on variables

Operators apply simple operations, such as addition and multiplication, to operands, such as numbers. They usually return a new value that is the result of the operation.

Most operators are binary, meaning that they work on two operands:

var result = FirstOperand operator SecondOperand;

Some operators are unary meaning they work on a single operand. A ternary operator works on three operands.

Experimenting with unary operators

Two common unary operators are used to increment ++ and decrement -- a number.

In Visual Studio, from the View menu, choose Other Windows, and then C# Interactive. Enter the following code:

> int i = 3;
> i
3

Note that when you enter a full statement ending in a semicolon, it is executed when you press Enter.

The first statement uses the assignment operator = to assign the value 3 to the variable i. When you enter a variable name at the prompt, it returns the variable's current value.

Enter the following statements and before pressing Enter, try to guess what the value of x and y will be:

> int x = 3;
> int y = x++;

Now check the values of x and y. You might be surprised to see that y has the value 3:

> x
4
> y
3

The variable y has the value 3 because the ++ operator executes after the assignment. This is known as postfix. If you need to increment before assignment, use prefix, as follows:

> int x = 3;
> int y = ++x;
> x
4
> y
4

You can decrement a variable using the -- operator.

Tip

Best Practice

Due to the confusion between prefix and postfix for the increment and decrement operators when combined with assignment, the Swift programming language designers plan to drop support for this operator in version 3. My recommendation for usage in C# is to never combine the use of ++ and -- operators with an assignment =. Perform the operations as separate statements.

Experimenting with arithmetic operators

Arithmetic operators allow you to perform arithmetics on numbers. Enter the following in the C# Interactive window:

> 11 + 3
14
> 11 - 3
8
> 11 * 3
33
> 11 / 3
3
> 11 % 3
2
> 11.0 / 3
3.6666666666666665

To understand the pide (/) and modulus (%) operators when applied to integers (whole numbers), you need to think back to primary school.

Imagine you have eleven sweets and three friends. How can you pide the sweets between your friends? You can give three sweets to each of your friends and there will be two left over. Those two are the modulus, also known as remainder. If you have twelve sweets, then each friend gets four of them and there are none left over. So the remainder is 0.

If you start with a real number (such as 11.0), then the pide operator returns a floating point value, such as 3.6666666666665, rather than a whole number.

Comparison and Boolean operators

Comparison and Boolean operators either return true or false. In the next chapter, we will use comparison operators in the if and while statements to check for conditions.