In this lesson, you will learn about C# Operators, Operators categories, and their usage, along with examples to better understand the topic.
In C#, operators are used to performing operations and manipulate variables.
There are four main categories of operators in C#
In C#, Arithmetic operators perform operations, such as addition or multiplication, on variables.
For Example, the below is an addition (+) operation in C#:
Arithmetic Operators are used to perform operations on both variables and values. For Example:
Arithmetic Operators Symbol | Arithmetic Operators’ Names | Example |
---|---|---|
+ | Addition | a + b |
– | Substraction | a – b |
* | Multiplication | a * b |
/ | Division | a / b |
% | Modulus | a % b |
** | Exponentiation | a ** b |
++ | Increment | a++ |
— | Decrement | a– |
Below is an example that covers all Arithmetic Operations in C#:
Assignment operators are another type of operator in C#, which is used to assign a value to a variable. For Example, the code below assigns a value of 5 to variable a.
int a = 5;
In addition, the Assignment operator +=
add a value to a variable.
For Example:
Assignment Operators Symbol | Explanation | Example |
---|---|---|
= | a = b + c will allocate the value of b + c into a |
a = b + c |
+= | a += b is same to a = b + a | a+=b |
-= | a -= b is same to a = a – b | a-=b |
*= | a *= b is same to a = a * b | a*=b |
/= | a /= b is same to a = a / b | a/=b |
%= | a %= b is same to a = a % b | a%=b |
&= | a &= b is same to a = a & b | a&=b |
|= | a |= b is same to a = a | b | a|=b |
^= | a ^= b is same to a = a ^ b | a^=b |
<<= | a <<= b is same to a = a << b | a <<= b |
>>= | a >>= b is same to a = a >> b | a >>= b |
Comparison operators are used to comparing between two values. If the condition is met, then the result is true. Otherwise, the result is false.
For example, the >
check if the value a is greater than value b:
Arithmetic Operators Symbol | Arithmetic Operators Name | Example |
---|---|---|
= | Equal | a = b |
! = | Not equal | a != b |
> | Greater than | a > b |
>= | Greater than equal to | a >= b |
< | Less than | a < b |
<= | Less than equal to | a <= b |
The last group of C# Operators is Logical Operators. They are used to determine the logic between two variables or values. For example, the code below explains the “and” operator &&
. It checks if “a” is less than 10 and “a” is greater than 4.
int a = 5;
Console.WriteLine(a < 10 && a >4 ); // Returns True
Logical Operators Symbol | Operators Name | Example |
---|---|---|
&& | AND | a && b |
|| | OR | a || b |
! | Not | !a |
This concludes the C# Operators Lesson. In the next lesson, you will learn about the string type in C#, string concatenation, and other topics related to the string reference type.