C# operators

What is Operator

An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Operators in C# are some special symbols that perform some action on operands.

Expressions perform specific actions, based on an operator, with one or two operands. An operand can be a constant, a variable or a function result. Operators are arithmetic, logical, and relational.

Operator Categories

C# has rich set of built-in operators and provides the following type of operators −

  1. Arithmetic Operators
  2. Relational Operators
  3. Logical Operators
  4. Bitwise Operators
  5. Assignment Operators
  6. Unary Operators
  7. Ternary Operators
  8. Misc. Operators

Arithmetic Operators

The arithmetic operators perform arithmetic operations on all the numeric type operands such as sbyte, byte, short, ushort, int, uint, long, ulong, float, double, and decimal.

OperatorNameDescriptionExample
+AdditionComputes the sum of left and right operands.int x = 5 + 5;
–SubtractionSubtract the right operand from the left operandint x = 5 – 1;
*MultiplicationMultiply left and right operandint x = 5 * 1;
/DivisionDivides the left operand by the right operandint x = 10 / 2;
%ReminderComputes the remainder after dividing its left operand by its right operandint x = 5 % 2;
++Unary incrementUnary increment ++ operator increases its operand by 1x++
—Unary decrementUnary decrement — operator decreases its operand by 1x–
+Unary plusReturns the value of operand+5
–Unary minusComputes the numeric negation of its operand.-5

Example of Arithmetical Operators

static void Main(string[] args)
        {
            int squarePerimeter = 17;
            double squareSide = squarePerimeter / 4.0;
            double squareArea = squareSide * squareSide;
            Console.WriteLine(squareSide); // 4.25
            Console.WriteLine(squareArea); // 18.0625
            int a = 5;
            int b = 4;
            Console.WriteLine(a + b); // 9
            Console.WriteLine(a + (b++)); // 9
            Console.WriteLine(a + b); // 10
            Console.WriteLine(a + (++b)); // 11
            Console.WriteLine(a + b); // 11
            Console.WriteLine(14 / a); // 2
            Console.WriteLine(14 % a); // 4
            int one = 1;
            int zero = 0;
            // Console.WriteLine(one / zero); // DivideByZeroException
            double dMinusOne = -1.0;
            double dZero = 0.0;
            Console.WriteLine(dMinusOne / zero); // -Infinity
            Console.WriteLine(one / dZero); // Infinity
            Console.ReadKey();
        }

Assignment Operators

The assignment operator = assigns its right had value to its left-hand variable, property, or indexer. It can also be used with other arithmetic, Boolean logical, and bitwise operators.

OperatorNameDescriptionExample
=AssignmentAssigns its right had value to its left-hand variable, property or indexer.x = 10;
x op= yCompound assignmentShort form of x =x op y where op = any arithmetic, Boolean logical, and bitwise operator.x += 5;
??=Null-coalescing assignmentC# 8 onwards, ??= assigns value of the right operand only if the left operand is nullx ??= 5;

Example

using System;
					
public class Program
{
	public static void Main()
	{
		int x,y;
		
		Console.WriteLine("x = 5 = {0}", x = 5);
		Console.WriteLine("y = (x = 5) = {0}", y = (x = 5));
		
	}
}

//OutPut
x = 5 = 5
y = (x = 5) = 5
using System;

public class Program
{
	public static void Main()
	{
		int x = 5;
		
		Console.WriteLine("x += 5 = {0}", x += 5);
		Console.WriteLine("x -= 5 = {0}", x -= 5);
		Console.WriteLine("x *= 5 = {0}", x *= 5);
		Console.WriteLine("x /= 5 = {0}", x /= 5);
	}
}

Output
x += 5 = 10
x -= 5 = 5
x *= 5 = 25
x /= 5 = 5
using System;
using System.Collections.Generic;

public class Program
{
	public static void Main()
	{
		string str = null;
		str ??= "Hello World";
		
		Console.WriteLine("str ??= {0}", str ??= "Hello World");
		
		IList<string> list = null;
		(list ??= new List<string>()).Add("test");
		
		Console.WriteLine("list ??= {0}", list[0]);
		
		int? x = null,y=null,z=null;
		x ??= y ??= z ??= 5;
		
		Console.WriteLine("x ??= {0}", x);
	
		
	}
}

Comparison Operators

Comparison operators compre two numeric operands and returns true or false.

OperatorDescriptionExample
<Returns true if the right operand is less than the left operandx < y;
>Returns true if the right operand is greater than the left operandx > y;
<=Returns true if the right operand is less than or equal to the left operandx <= y
>=Returns true if the right operand is greater than or equal to the left operandx >= y;

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

Equality Operators

The equality operator checks whether the two operands are equal or not.

OperatorDescriptionExample
==Returns true if operands are equal otherwise false.x == y;
!=Returns true if operands are not equal otherwise false.x != y;

Example

using System;
					
public class Program
{
	public static void Main()
	{
		int x = 5, y = 5;
		float f = 5.3f;
		
		Console.WriteLine(3 == 2);
		Console.WriteLine(x == y);
		Console.WriteLine(x == f);
	}
}
using System;
					
public class Program
{
	public static void Main()
	{
		int x = 5, y = 5;
		float f = 5.3f;
		
		Console.WriteLine(3 != 2);
		Console.WriteLine(x != y);
		Console.WriteLine(x != f);
	}
}

Boolean Logical Operators

The Boolean logical operators perform a logical operation on bool operands.

OperatorDescriptionExample
!Reverses the bool result of bool expression. Returns false if result is true and returns true if result is false.!false
&&Computes the logical AND of its bool operands. Returns true both operands are true, otherwise returns false.x && y;
||Computes the logical OR of its bool operands. Returns true when any one operand is true.x || y;

Example

static void Main(string[] args)
        {
            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
            Console.ReadKey();
        }

Types of Operators by Number of Arguments

Operators can be separated into different types according to the number of arguments they could take:

Operator precedence

In an expression with multiple operators, the operators with higher precedence are evaluated before the operators with lower precedence. In the following example, the multiplication is performed first because it has higher precedence than addition:

var a = 2 + 2 * 2;
Console.WriteLine(a); //  output: 6

Use parentheses to change the order of evaluation imposed by operator precedence:

var a = (2 + 2) * 2;
Console.WriteLine(a); //  output: 8

The following table lists the C# operators starting with the highest precedence to the lowest. The operators within each row have the same precedence.

OperatorsCategory or name
x.y, f(x), a[i], x?.y, x?[y], x++, x–, x!, new, typeof, checked, unchecked, default, nameof, delegate, sizeof, stackalloc, x->yPrimary
+x, -x, !x, ~x, ++x, –x, ^x, (T)x, await, &x, *x, true and falseUnary
x..yRange
switchswitch expression
withwith expression
x * y, x / y, x % yMultiplicative
x + y, x – yAdditive
x << y, x >> yShift
x < y, x > y, x <= y, x >= y, is, asRelational and type-testing
x == y, x != yEquality
x & yBoolean logical AND or bitwise logical AND
x ^ yBoolean logical XOR or bitwise logical XOR
x | yBoolean logical OR or bitwise logical OR
x && yConditional AND
x || yConditional OR
x ?? yNull-coalescing operator
c ? t : fConditional operator
x = y, x += y, x -= y, x *= y, x /= y, x %= y, x &= y, x |= y, x ^= y, x <<= y, x >>= y, x ??= y, =>Assignment and lambda declaration

Operator associativity

When operators have the same precedence, associativity of the operators determines the order in which the operations are performed:

CategoryOperatorsAssociativity
Postfix Increment and Decrement++, —Left to Right
Prefix Increment, Decrement and Unary++, –, +, -, !, ~Right to Left
Multiplicative*, /, %Left to Right
Additive+, –Left to Right
Shift<<, >>Left to Right
Relational<, <=, >, >=Left to Right
Equality==, !=Left to Right
Bitwise AND&Left to Right
Bitwise XOR^Left to Right
Bitwise OR|Left to Right
Logical AND&&Left to Right
Logical OR||Left to Right
Ternary? :Right to Left
Assignment=, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=Right to Left

Left-associative operators

Left-associative operators are evaluated in order from left to right. Except for the assignment operators and the null-coalescing operators, all binary operators are left-associative. For example, a + b - c is evaluated as (a + b) - c.

Right-associative operators

Right-associative operators are evaluated in order from right to left. The assignment operators, the null-coalescing operators, and the conditional operator ?: are right-associative. For example, x = y = z is evaluated as x = (y = z).

int a = 13 / 5 / 2;
int b = 13 / (5 / 2);
Console.WriteLine($"a = {a}, b = {b}");  // output: a = 1, b = 6

Operand evaluation

Unrelated to operator precedence and associativity, operands in an expression are evaluated from left to right. The following examples demonstrate the order in which operators and operands are evaluated:

ExpressionOrder of evaluation
a + ba, b, +
a + b * ca, b, c, *, +
a / b + c * da, b, /, c, d, *, +
a / (b + c) * da, b, c, +, /, d, *

Typically, all operator operands are evaluated. However, some operators evaluate operands conditionally. That is, the value of the leftmost operand of such an operator defines if (or which) other operands should be evaluated. These operators are the conditional logical AND (&&) and OR (||) operators, the null-coalescing operators ?? and ??=, the null-conditional operators ?. and ?[], and the conditional operator ?:. For more information, see the description of each operator.