C# Studies
Operators
Arithmetic Operators
- + = Addition
- - = Subtraction
*= Multiplication- / = Division
- % = Remainder of the division
int value = 2 + 2; // 4int value = 2 - 2; // 0int value = 2 * 2; // 4int value = 2 / 2; // 1int value = 2 % 2; // 0Assignment Operators
- = = Assigns a value
- += = Adds a new value to the current value
- -= = Subtracts a new value from the current value
*== Multiplies the current value by a new value- /= = Divides the current value by a new value
int x = 0; // Assigns a value to a variablex += 5; // same as x = x + 5; and results in x = 5x -= 1; // same as x = x - 1; and results in x = 4 (5 - 1 = 4)x *= 10; // same as x = x * 10; and results in 40 (4 * 10 = 40)x /= 2; // same as x = x / 2; and results in 20 (40 / 2 = 20)Comparison Operators
Return boolean values
=== Equal to!== Not equal to>= Greater than<= Less than>== Greater than or equal to<== Less than or equal to
5 == 5; // True4 != 3; // True4 != 4; // False6 > 5; // True4 < 5; // True4 <= 4; // True5 >= 3; // TrueConditional Operators
The conditional operator is a one-line construct to check two values using the ? and : operators, in the following structure:
<condition> ? <if true, returns this value> : <if false, returns this value>Let’s look at the following example:
int saleAmount = 1001;
int discount = saleAmount > 1000 ? 100 : 50;In the example above, if the value of saleAmount is greater than 1000, the variable discount receives 100; otherwise it receives 50.
Increment and Decrement Operators
→ We can change the value of a variable every time it is used
In C#, as in any high-level language, we can change the value of a variable every time we use it in a process.
| Symbol | What it does |
|---|---|
| ++ | Increments by 1 |
| — | Decrements by 1 |
- We can increment the value before using the variable
int x = 5;Console.WriteLine(++x); // 6- We can increment the value after using the variable
int x = 5;Console.WriteLine(x++); // 5Console.WriteLine(x); // 6- We can decrement the value before using the variable
int x = 5;Console.WriteLine(--x); // 4- We can decrement the value after using the variable
int x = 5;Console.WriteLine(x--); // 5Console.WriteLine(x); // 4Logical Operators
Return boolean values
Used for conditional operations
&&= Logical AND- All conditions must be true
||= Logical OR- At least one must be true
!= Logical NOT- Negates the value: true becomes false and vice versa
int x = 12;bool value = (x > 25) && (x < 40); // Falsebool value = (x > 25) || (x < 40); // Truebool value = !(x > 25) && (x < 40); // True