We will learn about the various operators available in C#.
Arithmetic Operators
These help to carry out basic arithmetic operations on numbers.
Arithmetic Operators | Name |
+ | Addition |
– | Subtraction |
* | Multiplication |
/ | Division |
% | Modulus |
++ | Increment |
– – | Decrement |
Let’s see these in action.
//Arithmetic operators
Console.WriteLine("Arithmetic Operators");
Console.WriteLine(10 + 10);
Console.WriteLine(100 - 10);
Console.WriteLine(10 * 10);
Console.WriteLine(20 / 10);
Console.WriteLine(12 % 10);
//Increment & Decrement operators only work with variables, properties, indexers
int myAge = 30;
myAge++;
Console.WriteLine(myAge);
int yourAge = 20;
yourAge--;
Console.WriteLine(yourAge);
Output:
Arithmetic Operators
20
90
100
2
2
31
19
Comparison Operators
As the name suggests, comparison operators are used to compare 2 values, returns a Boolean.
Comparison Operator | Name |
== | Equal to |
!= | Not Equal to |
> | Greater than |
< | Lesser than |
>= | Greater than or equal to |
<= | Lesser than or equal to |
Let’s see them in action.
//Comparison operators
Console.WriteLine("Comparison Operators");
Console.WriteLine(5 == 5);
Console.WriteLine(5 != 10);
Console.WriteLine(5 < 10);
Console.WriteLine(5 > 10);
Console.WriteLine(5 >= 10);
Console.WriteLine(5 <= 10);
Output:
Comparison Operators
True
True
True
False
False
True
Logical Operators
These operators are used with variables, expressions to determine the logic amongst them.
Let’s see them in action.
Operator | Description | Example |
&& | AND | num1 < 10 && num1 > 5 |
|| | OR | num1 == 10 || num1 == 5 |
! | NOT | !(num1 > 10) |
//Logical Operations
Console.WriteLine("Logical Operators");
int num1 = 100;
Console.WriteLine(num1 > 50 && num1 < 500);
Console.WriteLine(num1 == 100 || num1 == 50);
Console.WriteLine(!true);
Output:
Logical Operators
True
False
False
AND – Returns true only when both the expressions are true, returns false when any of the expressions are false
OR – Returns true when any one of the expressions are true
Logical operators when mixed with the assignment operator bring in more flavor in decision making, as demonstrated below.
num >=5 && num <=10;
num !=10 || num >=100;
We will be dealing with operators more and more in the upcoming articles.