In this article we will discuss about common operators that used in C#. Like any other programming languages C# has also some common operators. We can divide those as the following –
• Assignment Operator (=)
• Arithmetic Operators (+,-,*,/,%)
• Comparison Operators (==,!=,>,>=,<,<=)
• Conditional Operators (&&,||)
• Ternary Operator (?:)
• Null Coalescing Operator (??)
Now we will discuss about each of this operator in details.
Assignment Operator (=)
This is a very common operator in every programming language. It is used to assign a value in a variable. We can give a variable a value by this operator. Suppose we declare a variable by the following instruction-
Int variable_name;
Then this variable reserve some memory in RAM but no value is saved in those memory. We can assign value to those memory by using assignment operator as follows-
Int variable_name=5;
Now the value 5 is reserved in those memory blocks. So assignment operator is used to assign values.
Arithmetic Operators (+,-,*,/,%)
These operators are used to perform arithmetic operation. In many places of a program we need to perform many arithmetic operation. So it is important to understand these operators closely.
The “+” operator performs addition operation. Suppose we want to add two values. Then we can do that by the following-
Int a = 5+4; Or, Int a=5; Int b=6; Int result= a+b;
The “+” operator takes two operands and return the result of addition between those operands. Similarly “-” operator performs the subtraction operation between two operands. It will subtract its right side operand from left side operand and return the result. The multiplication operator is “*”. It will perform multiplication operation.
Now the two operator / and % is related to division operation. The forward slash (/) operator returns the quotient of the division operation and “%” (read as MOD) operator returns the reminder. To understand the difference we consider a division operation. Suppose we want to divide 10 by 2. So here the Quotient will be 5 and reminder will be 0. If we use / operator then it will return 5 and if we use % then it will return 0. Consider the following program-
using System; class Program { static void Main() { int Numerator = 10; int Denominator = 2; int result = Numerator / Denominator; Console.WriteLine("{0}", result); } }
The above program will print 5 because here we use / operator and it will return quotient. If we used % in place of / then it will print the reminder that is 0 here.
Comparison Operators (==,!=,>,>=,<,<=)
Comparison operators are used to compare to value and always return true or false. Every comparison operator has a meaning and performs a specific compare operation. The best example of this operator is in conditional statement. The statement in which we compare something in respect with some condition is called conditional statement. There are some keywords that used in conditional statement, one of this is “if” keyword. It is very common in almost all programming languages.
The double equal sign is used to compare equality. Consider the following example-
using System; class Program { static void Main() { int a = 10; if(a==10) { Console.WriteLine("{0}", a); } } }
In the above example we compare the value of variable with 10. If the value of variable a is equal to 10 then the next instruction will execute. The next instruction is to print the value of ‘a’ that is 10 here. So the program will print 10.
The “!=” operator is used to check inequality. For example in the above example we can check the variable ‘a’ is not equal or not. If we want to execute another instruction if the variable is not equal to 10 then code should be as follows-
using System; class Program { static void Main() { int a = 5; if(a==10) { Console.WriteLine("{0}", a); } if(a!=10) { Console.WriteLine("a is not equal to 10"); } } }
The above program will print “a is not equal to 10” because the value of a is 5 here. The != operator used here to execute the meaningful string that user can understand specifically that a is not equal to 10.
Similarly we can check greater than relation by the “>” operator. It will return true if the right side operand is greater than the left side operand. If we want to check greater or equal relation then we can use >= operator. It will return true if the left side operand is greater than right side operand and also if the operands are equal to each other.
Like greater than relation we can check less than relation by “<” operator and less than or equal relation by “<=” operator.
Conditional Operators (&&,||)
There are two operators that used in conditional statements named as AND (&&) and OR (||). If there is any situation where we need to execute a statement if and only if some of conditions are true then we can use && operator. This operator takes two condition and execute next instructions if all of those conditions are true. Suppose we have to check if a number is less than 5 and greater than 1 or not then we can check it by && operator as following-
using System; class Program { static void Main() { int a=2; if(a1 ) { Console.WriteLine("a is less than 5 and greater than 1"); } } }
In the above example two conditions is checked, one is a is less than 5 and the other is a is greater than 1. So the print instruction will be executed if each of these instruction are true. Another operator is || (OR) this operator used as the same of && operator but if any one of the condition is true between two then the next instruction will execute. The OR operator return true if any one of the condition is true. In the above example if we used OR operator then weather the value of a is less than 5 or greater than 1 the print instruction will execute.
using System; class Program { static void Main() { int a=10; if(a1 ) { Console.WriteLine("a is less than 5 OR greater than 1"); } } }
In the above example the condition a is less than 5 is false but a is greater than 1 true, so one of the condition is true. That’s why the print instruction will execute.
Ternary Operator (?:)
The ternary operator is a very interesting operator. It gives us two options if any condition is true than do something otherwise do something. The syntax of ternary operator can be written as follows-
Any Condition ? do if the condition is true : do if condition is false
We can see it by the following code-
using System; class Program { static void Main() { int a=10; bool ISValue10 = a == 10 ? true : false; Console.WriteLine("{0}", ISValue10); } }
In the above example the condition is if the variable “a” is equal to 10 or not. If it is true then the bool type variable “ISValue10” will be assigned by true otherwise false. Here the example will print true because here the value of variable is 10. We can do the same by if statement but it will take more instruction that we have done here with one instruction. That is the benefit of using ternary operator.
Null Coalescing Operator (??)
To understand null coalescing operator first we have to understand nullable types in C#. Actually we can divide the types in C# in two broad categories-
• Value types
• Reference types
In the previous article we have already seen the value types and those are- integer, double, float, decimal etc. We have also seen a reference type that is string type. String is actually a class. We will discuss about reference types and value types in details in the later session. What we need to understand at this point is types in C# can be divided in two broad categories that is value type and reference type. Example of value type is integer, float, double, structs, enums and example of reference type is interface, delegates, arrays, class etc. And another point we need to keep in mind at this point is the default value of a reference type is null and the default value for value type is some form of zero. For example the default value of type integer is zero and it cannot hold the value null. To assign null in a variable we use the keyword null in C#. If we try to assign null to a integer type variable then we will get an error. So value type cannot hold null value. But as I told before that string is a class that is reference type so we can assign a string variable with null. For an example we can write-
string s = null;
but we cannot write-
int a = null;
If we try to assign null to a integer type variable then it will return an immediate error. Sometimes it is necessary to assign a value types variable with the value null. Generally it is necessary if we use C# to communicate with a database. Since nullable types and non-nullable types is not a concept of database it is a concept of C#, any of the field in a database can be null. Sometimes for making decision it is necessary to assign null to value type variable. Again we get here two types, one is nullable and the other is non-nullable. We can assign null to non-nullable types by using the ? operator.
Suppose we have a form that ask the user a question “Are you a teacher?” and this field is optional. User can say yes or no and the user can also keep the field empty. If we have a bool type variable to store the answer then we can assign true or false in this variable nothing else. But if the user keep the field empty we need to assign null to bool type variable. We can do it by using ? operator as follows.
bool? ISUserTeacher = null;
So we can make a non-nullable type a nullable type by using ? operator. Now consider an example to understand null coalescing operator. Suppose a have 10 mangoes in a tree and we store the result in a integer type variable as follows-
int MangoesInTree = 10;
Now it is possible that there is no mangoes in the tree. So we have to make the integer variable a nullable variable that we can assign null value to it. We can do it as follows-
int? MangoesInTree = null;
Suppose we have another variable named availablemangoes and we will assign the value of MangoesInTree in it if MangoesInTree is not null. If MangoesInTree is null then we will assign 0 to availablemangoes variable. We can do it as follows-
using System; class Program { static void Main() { int? MangoesInTree = null; int availablemangoes; if(MangoesInTree==null) { availablemangoes = 0; } else { availablemangoes = MangoesInTree; } Console.WriteLine(“{0}”,availablemangoes); } }
Unfortunately we will get an error here that “cannot imlicitly convert type int? to int”. Here MangoesInTree variable is a nullable variable but availablemangoes is not a nullable variable so it cannot be assigned by the nullable types. Here we can use a way to do it. It is called type casting. We will discuss about type casting and implicit, explicit type conversion in the very next article. So just for now note it, we can do the above program as follows-
using System; class Program { static void Main() { int? MangoesInTree = null; int availablemangoes; if(MangoesInTree==null) { availablemangoes = 0; } else { availablemangoes = (int)MangoesInTree; } Console.WriteLine(“{0}”,availablemangoes); } }
Now it will print the value of availablemangoes as we wanted. But we can do the same program with just one line and this is what the null coalescing operator is. We can do the same program with null coalescing operator. The above program with null coalescing operator can be written as follows-
using System; class Program { static void Main() { int? MangoesInTree = 10; int availablemangoes; availablemangoes = MangoesInTree ?? 0; Console.WriteLine("{0}", availablemangoes); } }
Look closely to the above program here we do the same thing with just one line of code. Here the default value what we want to assign in non-nullable variable is given after the null coalescing operator (??) and before the operator we supply the value that we want to assign if the MangoesInTree variable is not null that is the variable itself. That is the purpose of null coalescing operator. It helps to assign a non-nullable types with nullable types in C#.