Overview of Operators in C#

Before starting with the detailed overview of operators in the  C#, it is important to have a brief understanding of what is it all about…

Introduction to Operator

An operator is a symbol or a character that represents an action. In C# we can make use of operators for making expressions. To calculate the value of a variable or performs an operation in the variable you will have to make a proper expression. These expressions are made using C# operators. You can overload many operators to change their meaning when applied to a user-defined type.

C# provides a wide range of operators as arithmetic operators, comparison operator, assignment operators, unary operators, logical operator etc. In this blog, you will learn deeply about all the C# operators with programming examples.

Types of Operators in C#

Following are the types of operators in C#:

Arithmetic Operator

In C# we can make use of arithmetic operators for performing arithmetic calculations such as addition, multiplication, subtraction, division, etc.

Operator Operator Name Example
+ Addition Operator 6 + 3 evaluates to 9
Subtraction Operator 10 – 6 evaluates to 4
* Multiplication Operator 4 * 2 evaluates to 8
/ Division Operator 25 / 5 evaluates to 5
% Modulo Operator (Remainder) 21 % 3 evaluates to 0

For example, see the below code:

using System;
 
namespace Operator
{
	class ArithmeticOperator
	{
		public static void Main(string[] args)
		{
			double firstNumber = 14.40, secondNumber = 4.60, result;
			int num1 = 26, num2 = 4, rem;

			// Addition operator
			result = firstNumber + secondNumber;
			Console.WriteLine("{0} + {1} = {2}", firstNumber, secondNumber, result);

			// Subtraction operator
			result = firstNumber - secondNumber;
			Console.WriteLine("{0} - {1} = {2}", firstNumber, secondNumber, result);

			// Multiplication operator
			result = firstNumber * secondNumber;
			Console.WriteLine("{0} * {1} = {2}", firstNumber, secondNumber, result);

			// Division operator
			result = firstNumber / secondNumber;
			Console.WriteLine("{0} / {1} = {2}", firstNumber, secondNumber, result);

			// Modulo operator
			rem = num1 % num2;
			Console.WriteLine("{0} % {1} = {2}", num1, num2, rem);
		}
	}
}

After running program, the output will be:

14.4 + 4.6 = 19
14.4 - 4.6 = 9.8
14.4 * 4.6 = 66.24
14.4 / 4.6 = 3.1304347826087
26 % 4 = 2

Relational Operator

In C# we can make use of relational operators for checking the relationship between two operands and if the relationship is correct or true the result will be true otherwise, it will result in false. Basically, Relational operators are used in decision making and looping statements.

Operators Description
== Equal to
> Greater than
< Less
>= Greater than equal to
<= Less than equal to
!= Not equal to

For example, see the below code:

using System;
 
namespace Operator
{
	class RelationalOperator
	{
		public static void Main(string[] args)
		{
			bool result;
			int firstNumber = 10, secondNumber = 20;

			result = (firstNumber==secondNumber);
			Console.WriteLine("{0} == {1} returns {2}",firstNumber, secondNumber, result);

			result = (firstNumber > secondNumber);
			Console.WriteLine("{0} > {1} returns {2}",firstNumber, secondNumber, result);

			result = (firstNumber < secondNumber);
			Console.WriteLine("{0} < {1} returns {2}",firstNumber, secondNumber, result);

			result = (firstNumber >= secondNumber);
			Console.WriteLine("{0} >= {1} returns {2}",firstNumber, secondNumber, result);

			result = (firstNumber <= secondNumber);
			Console.WriteLine("{0} <= {1} returns {2}",firstNumber, secondNumber, result);

			result = (firstNumber != secondNumber);
			Console.WriteLine("{0} != {1} returns {2}",firstNumber, secondNumber, result);
		}
	}
}

After running this program, the output will be:

10 == 20 returns False
10 > 20 returns False
10 < 20 returns True
10 >= 20 returns False
10 <= 20 returns True
10 != 20 returns True

Logical Operators

In C# logical operators are basically used in decision making and looping statements. These operators are used with boolean expressions (true/false).

Operator Meaning
|| OR
&& AND
! NOT

 

 

 

 

 

For example, see the below code:

using System;
 
namespace Operator
{
	class LogicalOperator
	{
		public static void Main(string[] args)
		{
			bool result;
			int firstNumber = 10, secondNumber = 20;

			// OR operator
			result = (firstNumber == secondNumber) || (firstNumber > 5);
			Console.WriteLine(result);

			// AND operator
			result = (firstNumber == secondNumber) && (firstNumber > 5);
			Console.WriteLine(result);
		}
	}
}

After running this program, the output will be:

True
False

Assignment Operator

Assignment operator assigns a specified value to another value. The usual assignment operator is ‘=’.

Example:

int amount=100;

After the execution of above statement, the value of amount becomes 100.

The use of compound statements

Operator Example Equivalent to
+= c+=1 c=c+1
-= c-=1 c=c-1
*= c*=1 c=c*1
/= c/=1 c=c/1
%= c%=1 c=c%1

The compound assignment operator combine simple assignment operator with another binary operator

For example, see the below code:

expression1+=expression2

Equal to

expression1=expression1+expression2

Or

production_amount=production_amount+4.5

above statement can be written as

production_amount+=4.5

Conditional Operator(?:)

The conditional operator works like an if else statement.

Its syntax is:

conditional expression? expression1 :expression2;

The meaning of above expression is as follows:

If the conditional expression is true then the result is expression1 otherwise result is expression2.

Let us understand this with the help of an example:

if(Sales>9000)? bonus=500 : bonus =0

If sales are greater than 9000 then the bonus will be 500 otherwise the bonus will be 0.

Size of Operator: This unary operator operates on a single value and we can use this operator to determine the size in terms of bytes.

For example, see the below code:

using System;

class Program
{
    static void Main()
    {
        //
        // Evaluate the size of some value types.
        // ... Invalid sizeof expressions are commented out here.
        // ... The results are integers printed on separate lines.
        //
        int size1 = sizeof(int);
        int size2 = 0; // sizeof(int[]);
        int size3 = 0; // sizeof(string);
        int size4 = 0; // sizeof(IntPtr);
        int size5 = sizeof(decimal);
        int size6 = sizeof(char);
        int size7 = sizeof(bool);
        int size8 = sizeof(byte);
        int size9 = sizeof(Int16); // Equal to short
        int size10 = sizeof(Int32); // Equal to int
        int size11 = sizeof(Int64); // Equal to long
        //
        // Print each sizeof expression result.
        //
        Console.WriteLine(
            "{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}\n{8}\n{9}\n{10}",
            size1, size2, size3, size4, size5, size6, size7, size8,
            size9, size10, size11);
    }
}

Output

4
0
0
0
16
2
1
1
2
4
8

The comma operator(,)

Comma operator in C# enables you to put more than one expression in a single line.

For example, see the below code:

main()
{

Int i=32,j=20;

//Rest of the program follows

}

Increment and decrement (++, –) operator

The Increment operator (++) and the decrement operator (–) increase or decrease by one the value stored in a variable. They are equal to +=1and to-=1, respectively.

For example, see the below code:

++x; x+=1; x=x+1;

All above expressions are equivalent in functionality because all of them increase the value of x by 1.

Bitwise operators ( &, |, ^, ~, <<, >> )

Basically, bitwise operators are used to perform bit-level operations on the operands. In this Operators are first converted to bit-level and then a calculation is performed on the operands. The mathematical operations such as addition(+),multiplication(*), subtraction(-),  etc. can be performed at bit-level for faster processing.

Operator

Description

Example

&

Binary AND Operator copy a bit to the result if it exists in both operands. (A & B) will result in 12 which is 0000 1100

|

Binary OR Operator which copies a bit if it exists in either operand. (A | B) will result in 61 which is 0011 1101

^

Binary XOR Operator which copies the bit if it is set in one operand but not both. (A ^ B) will result in 49 which is 0011 0001

~

Binary One’s Complement  Operator is unary and has the effect of ‘flipping’ bits. (~A ) will result in -61 which is 1100 0011 in 2’s complement form due to a signed binary number.

<<

Binary Left Shift Operator in which left-hand side operands value is moved left by the number of bits specified by the right operand. A << 2 will result in 240 which is 1111 0000

>>

Binary Right Shift Operator in which left-hand side operands value is moved right by the number of bits specified by the right operand. A >> 2 will result in 15 which is 0000 1111

Explicit type casting operators

Mainly explicit type casting operators allow you to convert a value of a given type to another type.

For example, see the below code:

int  i ;

float f = 3.14;

i = (int) f;

Above example converts the floating-point number to3.14 an integer value (3); Here, the typecasting operator is(int).

This can although be followed by another method using C#. In this method, the functional notation preceding the expression to be converted by the type and enclosing the expression between parentheses is considered.

i=int(f);

Operator Overloading in C#

In C#, we can overload the operators, means we can make use of same operators for doing the different task.for example, we can make use of a (+) operator to add two integer values and for concatenating two strings.

Overloaded Operators:

+ * / % ^
& | ~ ! , =
< > <= >= ++
<< >> == != && ||
+= -= /= %= ^= &=
|= *= <<= >>= [] ()
-> ->* new new [] delete delete []

Not Overloaded Operators:

:: .* . ?:

Operators are building blocks of any programming language. Without this, the functionality of any programming language is incomplete. So if you want to become expert in programming you should have proper knowledge of operators. I hope my article helps in understanding basic concepts of C#. In case of any other queries, you can surely post your valuable comments in the comments section below…

Leave a Comment