Now that you've seen how to declare and initialize
The operators available range from the simple to the highly complex, some of which you might never encounter outside of mathematical applications. The simple ones include all the basic mathematical operations, such as the
+
operator to add two operands, and the complex ones include manipulations of variable content via the binary representation of this content. There are also logical operators
In this chapter, you concentrate on the mathematical and assignment operators, leaving the logical ones for the
Operators can be
Unary operators, which act on single operands
Binary operators, which act on two operands
Ternary operators, which act on three operands
Most operators fall into the binary category, with a few unary ones, and a single ternary one called the conditional operator (the conditional operator is a logical one, that is it returns a Boolean value; this is discussed in Chapter 4).
Let's start by looking at the mathematical operators, which span both unary and binary categories.
There are five simple mathematical operators, two of which have binary and unary forms. In the next table, I've listed each of these operators, along with a quick example of its use and the results when it's used with simple numeric types (integer and floating point).
|
Operator |
Category |
Example Expression |
Result |
|---|---|---|---|
|
+ |
Binary |
var1 = var2 + var3; |
Var1 is assigned the value that is the sum of var2 and var3 . |
|
- |
Binary |
var1 = var2 - var3; |
Var1 is assigned the value that is the value of var3 subtracted from the value of var2 . |
|
* |
Binary |
var1 = var2 * var3; |
Var1 is assigned the value that is the product of var2 and var3 . |
|
/ |
Binary |
var1 = var2 / var3; |
Var1 is assigned the value that is the result of dividing var2 by var3 . |
|
% |
Binary |
var1 = var2 % var3; |
Var1 is assigned the value that is the remainder when var2 is divided by var3 . |
|
+ |
Unary |
var1 = +var2; |
Var1 is assigned the value of var2 . |
|
- |
Unary |
var1 = -var2; |
Var1 is assigned the value of var2 multiplied by –1. |
In this chapter, you covered a fair amount of ground on the way to creating usable (if basic) C# applications. You've
The major part of this chapter
You have also seen how you can assemble operators and operands into expressions and looked at the way these are executed, and the order in which this takes place.
Finally, you looked at namespaces, which will become more and more important as the book progresses. By introducing this topic in a
In this chapter, you learned:
How basic C# syntax works
What Visual Studio does when you create a console application project
How to understand and use variables
How to understand and use expressions
What a namespace is
So far, all of your programming has taken the form of