C# Operators with Examples

In C# Operators are used to from operation on variables and value. A number of operator type available in C#

  • Arithmetic operator: used for the simple mathematics operations
  • Assignment operator: used for assigning the values to variables.
  • Comparison Operator: used for the comparison of two literal or variables
  • Logical Operator: used to work with boolean data type as well as a boolean expression.
  • Conditional Operator: condition to be checked

In C# Operators can also be categorized according to the number of operands.

There are three categories of the operator according to the operands.

  • Unary operator: one operand
  • Binary operator: two operand
  • Ternary operator: three operand

Left-associated is a binary operator in c# its mean expression is calculated from left to right. On different data types, some C# operators perform different actions. 

Here are some examples of a C# operator.

int number = 17 + 9;
Console.WriteLine(number); // 25
string firstName = "shahzad";
string lastName = "hussain"; 
// Do not forget the space between them
string fullName = firstName + " " + lastName;
Console.WriteLine(fullName); // shahzad hussain

Output:

26
shahzad hussain

Arithmetic Operator

"+", "-", "*" and "/" are the arithmetic operator in C# same as math. Arithmetic operators perform Addition, Subtraction, Multiplication, and division on the numerical numbers and the result will be in numerical value. 

The division operator has a different effect on the integer value and real number. if two numbers for division are integer numbers then this type of division is known as integer division. and the result of this division will be an integer number. The remainder of integer numbers can be obtained by the "%"  sign.

On the other hand, if the division between two real numbers or two numbers and if one number is a real number then this type of division is known as real division and the result type of this division should be a real number.

Operator Name Description
+ Addition Adds left and right operands.
- Subtraction Subtract the second operand from the first operand
* Multiplication Multiply both operands
/ Division Divides the first operand by the second operand
% Reminder The operator returns the remainder when the first operand is divided by the second operand
++ Unary increment Increases integer value by one
-- Unary decrement Decreases integer value by one

Examples:

int result;
int First_variable = 10, Second_variable = 5;
// Addition operation
result = (First_variable + Second_variable);
Console.WriteLine("Addition -  " + result);
// Subtraction Operation
result = (First_variable - Second_variable);
Console.WriteLine("Subtraction - " + result);
// Multiplication Operation
result = (First_variable * Second_variable);
Console.WriteLine("Multiplication - " + result);
// Division operation
result = (First_variable / Second_variable);
Console.WriteLine("Division - " + result);
// Modulus Operation
result = (First_variable % Second_variable);
Console.WriteLine("Modulus - " + result);

Output:

Addition -  15
Subtraction - 5
Multiplication - 50
Division - 2
Modulus - 0

Now we will discuss the operator which are falling in the unary category.

  • Incremental operator               ++
  • Decremental operator             --

Increasing by one operator(++)  used for the additional one unit into the current value of the number and decreasing by one operator(--) is used for subtracting one unit from the number.

These two operators further dive into two categories

  • Post Increment            x++
  • Pre increment              x--
  • Post decrement           ++x
  • Pre decrement             --x

Examples:

int Number_ = 10, Result;
// post-increment 
Result = Number_++;
//Number_ will be 11 now 
Console.WriteLine("Number_ = {0} and Result = {1}", Number_, Result);
Result = Number_--;
//Number will be 10 now 
Console.WriteLine("Number_ = {0} and Result = {1}", Number_, Result);
//Pre Increment
Result = ++Number_; 
Console.WriteLine("Number_ = {0} and Result = {1}", Number_, Result);
//Pre Decrement
Result = --Number_;
Console.WriteLine("Number_ = {0} and Result = {1}", Number_, Result);

Output:

Number_ = 11 and Result = 10
Number_ = 10 and Result = 11
Number_ = 11 and Result = 11
Number_ = 10 and Result = 10

Assignment operator

  • In C# assignment is denoted with a single equal sign "="
  • The general form of the assignment operator will be variable_name = expression;
  • Through the assignment operator, we can generate a chain of assignments.
  • we can set a group of common values with the help of the chain of assignments.
Operator Description
= Assigns values from right side operands to left side operand
+= It is used to add the value of the right operand to the left operand and assigns the value to the left operand
-= It is used to subtract the value of the right operand value from the left operand value and assigns the value to the left operand
*= It is used to multiplies the right operand with the left operand and assigns the final value to the left operand
/= It is used to divides the left operand with the right operand and assign the final value to the left operand
%= It takes modulus using two operands and assigns the value to the left operand
<<= Left shift AND assignment operator
>>= Right shift AND assignment operator
&= Bitwise AND assignment operator
^= bitwise exclusive OR and assignment operator
|= bitwise inclusive OR and assignment operator

Cascade Assignment Operator

In C# assignment operator can be used as a cascade which means we can define more the one in a single expression for example.

int x, y, z;

x = y = z = 25;

Let's discuss the above example in the first line of the example we initialize 3 variables and in the second line, we will assign the value to these three variables.

Note: In C# the assignment operator is "=" while comparison operator is "==" if we will exchange these expressions then this will be the common error.

Compound Assignment Operator

In C# compound operators are used to reducing the size of code. let's make some understanding about compound assignment operator with the help of the below example.

int x = 2;
int y = 4;
x *= y; // Same as x = x * y;
Console.WriteLine(x); // 8

Output:

8

Common compound assignment operators.

+= : this common compound assignment operator is used to add the value of operand2 to operand1.

-=: used to subtract the value of the right operand value from the left operand value.

Some other common compound assignment operators are *= , %=.

Examples:

int number1 = 6;
int number2 = 4;
Console.WriteLine(number2 *= 10);  // 40
int result = number2 = 3;  // number2=3 and result=3
Console.WriteLine(result);     // 3
Console.WriteLine(number1 |= 1);  // 7
Console.WriteLine(number1 += 3);
Console.WriteLine(number1 /= 2);

Output:

40
3
7
10
5

Let's elaborate on the above example. First, we will initialize two integer type variables. On the third line, we print the value of the number2 with a compound assignment operator *=, If we will not use the compound operator then line three would be like this number2 = number2 * 10;

We have also applied some other compound operator you can check result simply put this code in the main() method of your program.

Conditional operator:

The conditional operator has three operands so these are the ternary operator. Syntax of the conditional operator. First of all, we will define the condition, for example, we have two variables first and second, we want to check the first variable is less than the second variable

first < second;

this will be the condition after that we will add? Sign.

//syntax
int first = 15, second = 30, Result;
Result = first < second ? first : second;
// To display the result 
Console.WriteLine("Result: " + Result);

Output:

Result: 15

Relational Operator

For the comparison of two values, we will use a comparison operator.

Operator Description Example
== The operator checks whether the two operands are equal or not. If they are equal then, it returns true. Otherwise, it returns false 5==5 will return true
!= The operator checks whether the two given operands are equal or not. If not, it returns true. Otherwise, it returns false 5!=5 will return false
> The operator checks whether the first operand is greater than the second operand 6>5 will return true
< The operator checks whether the first operand is lesser than the second operand. If so, it returns true 6>5 will return true
>= The operator checks whether the first operand is greater than or equal to the second operand 5>=5 will return true
<= The operator checks whether the first operand is lesser than or equal to the second operand 5<=5 will also return true

Example:

int x = 10, y = 5;
Console.WriteLine("x > y : " + (x > y));    // True
Console.WriteLine("x < y : " + (x < y));    // False
Console.WriteLine("x >= y : " + (x >= y));  // True
Console.WriteLine("x <= y : " + (x <= y));  // False
Console.WriteLine("x == y : " + (x == y));  // False
Console.WriteLine("x != y : " + (x != y));  // True

Output:

x > y : True
x < y : False
x >= y : True
x <= y : False
x == y : False
x != y : True

Logical Operator

In C# logical operator take booleans value and the result type should be boolean (true, false). Some basic logical operators are "And" denoted by (&&), "OR" denoted by (||), "Exclusive OR" denoted by (^), and "Logical Negotaion" denoted by !.

The following table will elaborate on the logical operator's operation.

x y !x x&&y x||y x^y
true true false true true false
true false false false true true
false true true false true true
false false true false false false
bool a = true;
bool b = false;
Console.WriteLine(a && b);// False
Console.WriteLine(a || b);// True
Console.WriteLine(!b);// True
Console.WriteLine(b || true);// True
Console.WriteLine((5 > 7) ^ (a == b));  // False

Output:

False
True
True
True
False

Laws of De-Morgan

In C# logical operator are governed by the De-Morgan Law

!(a && b) == (!a || !b)

!(a || b) == (!a && !b)

Other Operators

Let's discuss some other common operators which will be used in our future lectures.

The "." Operator

"." is an access operator is used to access the members of a class or an object. for better understanding about "." operator let's see the usage of this operator.

Console.WriteLine(DateTime.Now); //Prints the date + time

Output:

1/12/2021 4:22:03 PM

In the above example, we print the current date and time. DateTime is a predefined or built-in C# class after the name of the class we will use. operator to access the different functions of this class.

Square Brackets [] Operator

[] are used to access the element of an array also called indexer.

int[] arr = { 1, 2, 3 };
Console.WriteLine(arr[0]); // 1

Output:

1

Brackets operator

This operator used to override the priority of the program execution.

'As' Operator

This operator is used for type conversion.

' is' Operator

This operator used to check that an object is compatible with the given object type. There are many more operators that we will discuss in future lectures.

Some Examples:

int a = 6;
int b = 3;
Console.WriteLine(a + b / 2);   // 7
Console.WriteLine((a + b) / 2); // 4
string name = "shahzad";
Console.WriteLine(name is string); // True

Output

7
4
True