C# Operators

An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations between the two operands. For example, in mathematics the plus symbol (+) signifies the sum of the left and right numbers. Similarly, in C#, we can do addition operation by using '+' operand.

In C#, there are several operators to perform various operations between multiple operands. C# has many operators that have different meanings based on the data types of the operands.

C# operators can be divided into following categories:

  1. Arithematic Operators
  2. Assignment Operators
  3. Relational Operators
  4. Logical Operators
  5. Bitwise and Shift Operators

Arithematic Operators in C#

Arithmetic operators are used to perform common mathematical operations:

For all these example, let's assume x= 10, y =5:

Operator Name Description Example
+ Addition Adds two operands x+y=15
- Subtraction Subtracts one value from another x-y=5
* Multiplication Multiplies two values x*y=50
/ Division Divides one value from another x/y=2
% Modulus Returns the division remainder x % y = 0 ( if, x = 3, y = 2, then x % y =1 )
++ Increment Increment operator increases integer value by 1 x++ = 11
-- Decrement Decreases the value of a variable by 1 x-- = 9

There are certain operators which have different meanings based on the datatype of the operand.

For example, if the + operator is used with numbers, it will add the numbers but if it is used with strings, it will concatenate the two strings.

string x="Hello";
string y = "World";

string z= x+y;

Console.WriteLine(z); //output = Hello World

Assignment Operators in C#

Assignment operators are used to assign values to variables. "=" is called the assignment operator. "=" assigns the variable in the left of it with the value on the right of it. Basically, it provides the data on its R.H.S. to the variable in its L.H.S.

Example:

int x=5;

take a look at more complete example

    using System;
    namespace Operator
    {
    	class AssignmentOperatorInCsharp
    	{
    		public static void Main(string[] args)
    		{
    			int FirstInt, SecondInt;
    			// Assigning a constant to variable
    			FirstInt = 5;
    			Console.WriteLine("First number = " + FirstInt);
    			// Assigning a variable to another variable
    			SecondInt = FirstInt;
    			Console.WriteLine("Second number = "+ SecondInt);
    		}
    	}
    }

Output :

First number = 5
Second number = 5

Relational Operators in C#

Relational operators are used to compare values, basically they check the relation between two data, and always return boolean results ( true or false)

Symbol Name Explanation Example
> Greater than This symbol is used to verify that data on the left of it is greater than the data on its right.

if x=5 , y=2;

x > y

< less than This symbol is used when the data on the left of it is smaller than the data on its right.

if x= 2, y=5;

x < y

<= less than or equal to This symbol is used when the data on the left of it is smaller than or equal to the data on its right.

if x= 3, y=4; OR x=4,y=4

x <=y

>= greater than or equal to This symbol is used when the data on the left of it is greater or equal to than the data on its right.

if x= 4, y=3; OR x=4,y=4

x >= y

== equal to This symbol is used when the data on the left of it is equal to the data on its right.

if x=5 , y=5

x==5

!= not equal to This symbol is used when the data on the left of it is not equal to the data on its right.

if x = 4, y=5

x !=y

Let's take a sample example program for above explained operators

using System;
					
public class Program
{
	public static void Main()
	{
		    Console.WriteLine(3 < 4);
            Console.WriteLine(3 == 4);
            Console.WriteLine(4 >= 3);
            Console.WriteLine(4 != 3);
		    Console.WriteLine(4 <= 3);
	}
}

Output

True
False
True
True
False

In the above code example, we have 5 expressions. These expressions compare integer values.

The result of each of the expressions is either true or false.

Logical operators in C#

Logical operators in C# are used to perform operations like AND, OR , NOT operations on any given operands. Here is the list of C# logical operators with meaning

Operator Name Meaning
|| Logical OR Operator

It is also called logical or bitwise OR.

If any of the two operands is non-zero then the condition becomes true, otherwise false

&& Logical AND Operator

It is also called logical or bitwise AND.

If both the operands are non-zero then the condition becomes true, otherwise false

! Logical NOT Operator

It computes logical negation of its operand. 

It produces true, if the operand evaluates to false, and false, if the operand evaluates to true

Let's take a look at the complete example which uses all three operators

using System;
					
public class LogicalOperatorProgram
{
	public static void Main()
	{
            bool result;
			int FirstInt = 20, secondInt = 30;
			// OR operator
			result = (FirstInt == secondInt) || (FirstInt > 5);
			Console.WriteLine(result);
		
			// AND operator
			result = (FirstInt == secondInt) && (FirstInt > 5);
			Console.WriteLine(result);
		
		   bool ThirdValue=false;
		   result = !ThirdValue;
		   Console.WriteLine(result);
	}
}

Output

True
False
True

Bitwise and shift Operators in C#

Bitwise operators are used to perform operations in bits and and perform bit by bit operation. Bitwise and shift operations never cause overflow and produce the same results in checked and unchecked contexts.

Here is the table for it.

Operator Name Meaning
~ Bitwise Complement Operator The ~ operator produces a bitwise complement of its operand by reversing each bit
<< Left-Shift Operator

The << operator shifts its left-hand operand left by the number of bits defined by its right-hand operand.

It discards the high-order bits that are outside the range of the result type and sets the low-order empty bit positions to zero

>> Right Shift Operator

The >> operator shifts its left-hand operand right by the number of bits defined by its right-hand operand.

It discards the low-order bits.

| Binary OR Operator

The | operator computes the bitwise OR of its operands.

Gives true if any 1 of the 2 operands is true

& Binary AND Operator

The & operator computes the bitwise logical AND of its operands

Gives true if both of the operands are true.

^ Binary XOR Operator

The ^ operator computes the bitwise logical exclusive OR, also known as the bitwise logical XOR, of its operands.

Let's take a look at complete example which includes all of the above operators

using System;
					
public class BitwWiseProgram
{
	public static void Main()
	{
		        int FirstValue = 10;
			int SecondValue = 20;
			int result;
			result = ~FirstValue;
			Console.WriteLine("~{0} = {1}", FirstValue, result);
			result = FirstValue & SecondValue;
			Console.WriteLine("{0} & {1} = {2}", FirstValue,SecondValue, result);
			result = FirstValue | SecondValue;
			Console.WriteLine("{0} | {1} = {2}", FirstValue,SecondValue, result);
			result = FirstValue ^ SecondValue;
			Console.WriteLine("{0} ^ {1} = {2}", FirstValue,SecondValue, result);
			result = FirstValue << 2;
			Console.WriteLine("{0} << 2 = {1}", FirstValue, result);
			result = FirstValue >> 2;
			Console.WriteLine("{0} >> 2 = {1}", FirstValue, result);
	}
}

Output

~10 = -11
10 & 20 = 0
10 | 20 = 30
10 ^ 20 = 30
10 << 2 = 40
10 >> 2 = 2

Ternary operator in C# (? :)

The conditional operator ?:, also known as the ternary conditional operator, evaluates a Boolean expression and returns the result of one of the two expressions.

The ternary operator ? : operates on three operands.

Syntax for

result = condition ? expression1 : expression2

The condition expression must evaluate to true or false. If condition evaluates to true, the expression1 is evaluated, and its result becomes the result of the operation.

If condition evaluates to false, the alternative expression2 is evaluated, and its result becomes the result of the operation. Only consequent or alternative is evaluated.

Example:

using System;
					
public class TernaryOperatorProgram
{
	public static void Main()
	{
	   int input = new Random().Next(-5, 5);

       string classify;


        classify = (input >= 0) ? "nonnegative" : "negative";

		Console.WriteLine("Input ="+input);
		Console.WriteLine("Classify ="+ classify);
	}
}

Output

Input =-3
Classify =negative

Share Tweet