Close
Close

C# Operators


In C#, there are symbols which tell the compiler to perform certain operations. These symbols are known as operators. For example, (+) is an operator which is used for adding two numbers similar to addition in Maths.

C# provides different types of operators:

  • Arithmetic Operators
  • Relational Operators
  • Increment and Decrement Operators
  • Logical Operators
  • Assignment Operators

C# Arithmetic Operators


Arithmetic Operators are the type of operators which take numerical values as their operands and return a single numerical value.

Let's assume the values of a and b to be 8 and 4 respectively.

Operator Description Example
+ Adds operands a+b=12
- Subtracts second operand from first a-b=4
* Multiplies both operands a*b=32
/ Divides numerator by denominator. a/b=2
% Modulus Operator returns the remainder of an integer division. a%b=0
using System;

class Test
{
static void Main(string[] args)
{
  int a=10, b=2;

  Console.WriteLine("a+b = " + (a+b));
  Console.WriteLine("a-b = " + (a-b));
  Console.WriteLine("a*b = " + (a*b));
  Console.WriteLine("a/b = " + (a/b));
}
}
Output
a+b = 12
a-b = 8
a*b = 20
a/b = 5

int a = 10, b = 2 → We are declaring two integer variables a and b and assigning them the values 10 and 2 respectively.

Inside Console.WriteLine, "a+b = " is written inside (" "), so it got printed as it is without evaluation. Then (a+b) after + is evaluated (i.e., 12) and printed.

So, "a+b = " combined with the calculated value of a+b i.e. (10+2 i.e. 12) and a+b = 12 got printed.

Let's take one more example.

using System;

class Test
{
static void Main(string[] args)
{
  int a=10, b=2;

  int z = a+b;

  Console.WriteLine("a+b = " + z);
}
}
Output
a+b = 12

In this example, z is assigned the value of a+b i.e., 12. Inside WriteLine, a+b = is inside " ", so it got printed as it is (without evaluation) and then the value of z i.e., 12 got printed. So, a+b = 12 got printed.

When an integer is divided by another integer, the answer is rounded off to the nearest lower integer.

When we divide two integers, the result is an integer. For example, 7/3 = 2 (not 2.33333).

To get the exact decimal value of the answer, at least one of numerator or denominator should have a decimal value.

For example, 7/3.0, 7.0/3 and 7.0/3.0 return 2.33333 because at least one of the operands in each case has a decimal value.

using System;

class Test
{
static void Main(string[] args)
{
  Console.WriteLine("3/2 = " + (3/2));
  Console.WriteLine("3/2.0 = " + (3/2.0));
  Console.WriteLine("3.0/2 = " + (3.0/2));
  Console.WriteLine("3.0/2.0 = " + (3.0/2.0));
}
}
Output
3/2 = 1
3/2.0 = 1.5
3.0/2 = 1.5
3.0/2.0 = 1.5

As we have seen that 3/2 (both int) is giving 1 whereas 3.0/2 or 3/2.0 or 3.0/2.0 (at least one is double) is giving us 1.5.

Suppose we are using two integers in our program and we got a need to get a double result after division, we can easily convert them to double during the time of division using explicit conversion. For example, (double)a/b.

converting int to double in C#

Let's look at an example.

using System;

class Test
{
static void Main(string[] args)
{
  int a = 5;
  int b = 2;

  Console.WriteLine((double)a/b);
}
}
Output
2.5

We casted the variable a to double during the division ((double)a/b) and we got a double result (2.5).

C# Relational and Equality Operators


Relational Operators check the relationship (comparison) between two operands. It returns true if the relationship is true and false if it is false.

Following is the list of relational operators in C#.

Again, assume the value of a to be 8 and that of b to be 4.

Operator Description Example
== Equal to (a == b) is false
!= Not equal to (a != b) is true
> Greater than (a > b) is true
< Less than (a < b) is false
>= Greater than or equal to (a >= b) is true
<= Less than or equal to (a <= b) is false

Let's see an example to understand the use of these operators.

using System;

class Test
{
static void Main(string[] args)
{
  int a = 5;
  int b = 4;

  Console.WriteLine(a == b);
  Console.WriteLine(a != b);
  Console.WriteLine(a > b);
  Console.WriteLine(a < b);
  Console.WriteLine(a >= b);
  Console.WriteLine(a <= b);
}
}
Output
False
True
True
False
True
False

In the above example, the value of a is not equal to b, therefore a == b (equal to) returned false and a !=b (not equal to) returned true.

Since the value of a is greater than b, therefore a > b (greater than) and a >= b (greater than or equal to) returned true whereas a < b (less than) and a <= b (less than or equal to) returned false.

C# Difference between = and ==


Although = and == seem to be the same, but they are quite different from each other. = is an assignment operator while == is an equality operator.

= assign values from its right side operands to its left side operands whereas == compares values and check if the values of two operands are equal or not.

difference between = and == in C#

Take two examples.

x = 5
x == 5

By writing x = 5, we assigned a value 5 to x, whereas by writing x == 5, we checked if the value of x is 5 or not.

C# Logical Operators


In C#, if we write A and B, then the expression is true if both A and B are true. Whereas, if we write A or B, then the expression is true if either A or B or both are true.

A and B → Both A and B

A or B → Either A or B or both.

The symbol for AND is && while that of OR is ||.

Assume the value of a and b to be true.

Operator Description Example
&& Logical AND. If both the operands are non-zero, then the condition becomes true (a && b) is true
|| Logical OR. If any one or both the operands are non-zero, then the condition becomes true (a || b) is true
! Logical NOT. It is used to reverse the condition. So, if a condition is true, ! makes it false and vice versa. (!(false)) is true

In Logical AND (&&) operator, if anyone of the expression is false, the condition becomes false. Therefore, for the condition to become true, both the expressions must be true.

For example, (3>2)&&(5>4) returns true because both the expressions (3>2 as well as 5>4) are true. Conditions (3>2)&&(5<4), (3<2)&&(5>4) and (3<2)&&(5<4) are false because at least one of the expressions is false in each case.

For Logical OR (||) operator, the condition is only false when both the expressions are false. If any one expression is true, the condition returns true. Therefore, (3<2)||(5<4) returns false whereas (3>2)||(5<4), (3<2)||(5>4) and (3>2)||(5>4) returns true.

Not (!) operator converts true to false and vice versa. For example, !(4<7) is true because the expression (4<7) is false and the ! operator makes it true.

using System;

class Test
{
static void Main(string[] args)
{
  int a = 5, b = 0;

  Console.WriteLine("(a>b) && (b==a) = " + ((a>b) && (b==a)));
  Console.WriteLine("(a>b) || (b==a) = " + ((a>b) || (b==a)));
  Console.WriteLine("!(a > b) = " + !(a > b));
}
}
Output
(a>b) && (b==a) = False
(a>b) || (b==a) = True
!(a > b) = False

In the expression (a>b) && (b==a), since b==a is false, therefore the condition became false. Since a>b is true, therefore the expression (a || b) became true. The expression a>b is true (since the value of a is greater than b) and thus the expression !(a>b) became false.

Before going further to learn about more different operators, let's look at the precedence of operators i.e., which operator should be evaluated first if there are more than one operators in an expression like 2/3+4*6.

C# Precedence of Operators


If we have written more than one operation in one line, then which operation should be done first is governed by the following rules :- Expressions inside brackets '()' are evaluated first. After that, this table is followed (The operator at the top has higher precedence and that at the bottom has the least precedence). If two operators have the same precedence, then the evaluation will be done in the direction stated in the table.

Operator Associativity
++ -- ! Right to left
* / % Left to right
+ - Left to right
> >= < <= Left to right
== =! Left to right
&& Left to right
|| Left to right
= += -= *= /= %= Right to left

Let's consider an expression

n = 4 * 8 + 7

Since the priority order of multiplication operator ( * ) is greater than that of addition operator ( + ), so first 4 will get multiplied with 8 and after that 7 will be added to the product.

Suppose two operators have the same priority order in an expression, then the evaluation will start from left or right as shown in the above table. For example, take the following expression:

10 / 5 + 2 * 3 -8

Since the priorities of / and * are greater than those of + and -, therefore / and * will be evaluated first. But / and * have the same priority order, so these will be evaluated from left to right (as stated in the table) simplifying to the following expression.

2 + 2 * 3 - 8

After /, * will be evaluated resulting in the following expression:

2 + 6 - 8

Again + and - have the same precedence, therefore these will also be evaluated from left to right i.e., first 2 and 6 will be added after which 8 will be subtracted resulting in 0.

If you don't want to remember these rules, then just put the expression you want to execute first in brackets. Eg- If you want to divide the product of (2+2) and 444 by the quotient of (999/5), then write the expression as - ((2+2)*444)/(999/5). This will get evaluated as (4*444)/(999/5) and finally get simplified to 1776/199 (as 999/5 is 199 and not 199.8).

C# Assignment Operators


Assignment Operators are used to assign values from its right side operands to its left side operands. The most common assignment operator is =.

a = 10 means that we are assigning a value 10 to the variable a.

Assignment operators assign values of right side operands to the left side but not vice-versa. So, 10 = a is invalid because we can't change the value of 10 to a.

There are more assignment operators which are listed in the following table.

Operator Description Example
= Assigns value of right operand to left operand C = A+B is same as C = A + B
+= Adds the value of right operand to left operand and assigns the final value to the left operand C += A is same as C = C + A
-= Subtracts the value of right operand from left operand and assigns the final value to the left operand C -= A is same as C = C - A
*= Multiplies the value right operand to left operand and assigns the final value to the left operand C *= A is same as C = C * A
/= Divides the value of left operand from right operand and assigns the final value to the left operand C /= A is same as C = C / A
%= Takes modulus using two operands and assigns the result to the left operand C %= A is same as C = C % A

Before going further, let's have a look at an example:

using System;

class Test
{
static void Main(string[] args)
{
  int a = 7;
  a = a+1;
  Console.WriteLine(a);
  a = a-1;
  Console.WriteLine(a);
}
}
Output
8
7

'=' operator starts from the right. eg.- if a is 4 and b is 5, then a = b will change a to 5 and b will remain 5.

a = a+b → Since '+' has a higher priority than '=', so, a+b will be calculated first. After this, '=' will assign the value of the sum a+b to a.

In the exact same fashion, in a = a+1, a+1 will be calculated first since + has higher priority than =. Now, the expression will become a = 8 making the value of a equal to 8.

Similarly, a = a-1 will make the value of a equal to 7 again.

Let's look at an example where different assignment operators are used.

using System;

class Test
{
static void Main(string[] args)
{
  int a = 7;
  Console.WriteLine("a += 4 Value of a: " + (a += 4));
  Console.WriteLine("a -= 4 Value of a: " + (a -= 4));
  Console.WriteLine("a *= 4 Value of a: " + (a *= 4));
  Console.WriteLine("a /= 4 Value of a: " + (a /= 4));
  Console.WriteLine("a %= 4 Value of a: " + (a %= 4));
}
}
Output
a += 4 Value of a: 11
a -= 4 Value of a: 7
a *= 4 Value of a: 28
a /= 4 Value of a: 7
a %= 4 Value of a: 3

To understand this, consider the value of a variable n is 5. Now if we write n += 2, the expression gets evaluated as n = n+2 thus making the value of n 7 (n = 5 + 2).

In the above example, initially, the value of a is 7.

The expression a += 4 gets evaluated as a = a+4 thus making the value of a as 11. After this, the expression a -= 4 gets evaluated as a = a-4 thus subtracting 4 from the current value of a (i.e. 11) and making it 7 again. Similarly, other expressions will get evaluated.

C# Increment and Decrement Operators


++ and -- are called increment and decrement operators respectively.

++ adds 1 to the operand whereas -- subtracts 1 from the operand.

a++ increases the value of a variable a by 1 and a-- decreases the value of a by 1.

Similarly, ++a increases the value of a by 1 and --a decreases the value of a by 1.

In a++ and a--, ++ and -- are used as postfix whereas in ++a and --a, ++ and -- are used as prefix.

For example, suppose the value of a is 5, then a++ and ++a changes the value of a to 6. Similarly, a-- and --a changes the value of a to 4.

C# Difference between Prefix and Postfix


While both a++ and ++a increases the value of 'a', the only difference between these is that a++ returns the value of a before the value of a is incremented and ++a first increases the value of a by 1 and then returns the incremented value of a.

Similarly, a-- first returns the value of a and then decreases its value by 1 and --a first decreases the value of a by 1 and then returns the decreased value.

Let's look at the example given below.

using System;

class Test
{
static void Main(string[] args)
{
  int a=8, b=8, c=8, d=8;
  Console.WriteLine("a++:  Value of a: " + (a++));
  Console.WriteLine("++b: Value of a: " + (++b));
  Console.WriteLine("c--: Value of a: " + (c--));
  Console.WriteLine("--d: Value of a: " + (--d));
}
}
Output
a++: Value of a: 8
++b: Value of a: 9
c--: Value of a: 8
--d: Value of a: 7

In a++, postfix increment operator is used with a which first printed the current value of a (8) and then incremented it to 9.

Similarly in ++b, the prefix operator first added one to the current value of b thus making it 9 and then printed the incremented value. The same will be followed for the decremented operators.

C# sizeof


sizeof() operator is used to get the size of data type. We can use the sizeof operator to get the size of int as 4. Let's look at the example given below.

using System;

class Test
{
static void Main(string[] args)
{
  Console.WriteLine("size of int : " + sizeof(int));
  Console.WriteLine("size of long : " + sizeof(long));
  Console.WriteLine("size of unsigned int : " + sizeof(uint));
  Console.WriteLine("size of boolean : " + sizeof(bool));
  Console.WriteLine("size of short : " + sizeof(short));
  Console.WriteLine("size of unsigned short : " + sizeof(ushort));
  Console.WriteLine("size of double : " + sizeof(double));
  Console.WriteLine("size of char: " + sizeof(char));
}
}
Output
size of int : 4
size of long : 8
size of unsigned int : 4
size of boolean : 1
size of short : 2
size of unsigned short : 2
size of double : 8
size of char: 2

C# typeof


typeof() operator is used to get the type of a data type. We can use the typeof operator to get the type of int as System.Int32. Let's look at the example given below.

using System;
class Test
{
static void Main(string[] args)
{
  Console.WriteLine("size of int : " + typeof(int));
  Console.WriteLine("size of long : " + typeof(long));
  Console.WriteLine("size of unsigned int : " + typeof(uint));
  Console.WriteLine("size of boolean : " + typeof(bool));
  Console.WriteLine("size of short : " + typeof(short));
  Console.WriteLine("size of unsigned short : " + typeof(ushort));
  Console.WriteLine("size of double : " + typeof(double));
  Console.WriteLine("size of char: " + typeof(char));
}
}
Output
size of int : System.Int32
size of long : System.Int64
size of unsigned int : System.UInt32
size of boolean : System.Boolean
size of short : System.Int16
size of unsigned short : System.UInt16
size of double : System.Double
size of char: System.Char

C# Math Class


What if you want to take sine, cosine or log of a number? Yes, we can perform such mathematical operations in C# by using the Math class inside System namespace in C#. It contains many useful mathematical functions. Let's have a look at some important methods of the Math class.

If you are not aware of these mathematical functions, then don't go into these and continue your coding part.
Function Description
Sin Calculates the sine value of some angle in radians
Cos Calculates the cosine value of some angle in radians
Ceiling Calculates the number which is equal to the integer just greater than the number passed
Floor Calculates the number which is equal to the integer just smaller than the number passed
Abs Calculates the absolute value of a number
Round Rounds a float or a double to the nearest integer or to the specified number of fractional digits.
Sqrt Calculates the square root of a number
Pow It takes two numbers as parameters and returns the value of the first number raised to the power equal to the second number
Log Returns the logarithm of a number.
Log10 Returns the logarithm of a number with base 10.

Let's look at an example using some of these functions.

using System;

class Test
{
static void Main(string[] args)
{
  Console.WriteLine(Math.Sin(Math.PI));
  Console.WriteLine(Math.Cos(Math.PI));
  Console.WriteLine(Math.Abs(-1));
  Console.WriteLine(Math.Floor(3.4));
  Console.WriteLine(Math.Ceiling(3.4));
  Console.WriteLine(Math.Pow(4, 2));
  Console.WriteLine(Math.Log10(100));
  Console.WriteLine(Math.Sqrt(4));
}
}
Output
1.22460635382238E-16
-1
1
3
4
16
2
2

With this chapter, we have covered all the basics required to enter the real programming part. From the next chapter, you will see a new part of programming.


Ask Yours
Post Yours
Doubt? Ask question