Lesson 4: Operators
At the end of this lesson, you should be able to answer the following:
- What is an operator?
- What is an expression?
- What are some of the commonly used operators in C#?
In the previous lesson, we mentioned that the type of a value can determine the operations that can be performed with it.
For example, we can add two integers:
10 + 2
+symbol between the two numbers is an operator. It represents an action or operation that can be done to the values supplied with it. The
+operator here is the same used in arithmetic addition.
The whole line above is called an expression. An expression can be evaluated further by C# to produce a new value.
Type the line into your code box and run the program. You'll see that C# evaluates the expression and displays the result.
Why did it display the result even if we didn't call
Dotnet Interactive is also a REPL environment. REPL stands for "read-evaluate-print loop". REPL environments allow quick evaluation of an expression, after which the output is displayed.
If we write more than one statement in the code box, it won't be a single expression anymore. Instead of doing the read-evaluate-print loop, Dotnet Interactive will compile the program as a whole.
We can also do subtraction, multiplication, and division. Each has its own operator.
10 - 2 // subtraction
10 * 2 // multiplication
10 / 2 // division
Type each line in the code box one at a time and run the program each time. The output will be the result of the arithmetic expression.
If you try to write all of them at the same time and run the program, you'll get an error.
10 + 2;
10 - 2;
10 * 2;
10 / 2;
Even if we put semicolons at the end of each line, the program will still be invalid!
That's because expressions are not valid statements. As we learned in Lesson 1, C# programs are made up of statements. Expressions in C# programs must be used as part of a valid statement.
What's a statement we've already learned? That's right, the
Wrap each expression into a
Console.WriteLine(10 + 2);
Console.WriteLine(10 - 2);
Console.WriteLine(10 * 2);
Console.WriteLine(10 / 2);
The result of each expression is now displayed.
Here are the common operators in C#.
These operators work with numeric values.
These operators compare two values. The result will either be
Greater than or equal to
Less than or equal to
Not equal to
Is the following an expression? Why or why not?
"100 + 25"
True or False: An expression by itself is a valid statement.
Wrap each example in the list of operators into a
Console.WriteLinestatement. Can you guess what each result will be?