Different Operators in C#

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#.

Advertisements

Reading and Writing to the Console

In the previous article we discussed about the basic structure of a C# program. Today we will see reading and writing operation to the console. We will see a little more interactive sample program than the previous today. Our program will ask the user his/her name and then print a welcome message with the name of the user which he/she just enter.

To write something to the console we have two methods under System namespace, one is Write and the other is WriteLine. Only the difference between these two is, if we use WriteLine then after writing something to the console it will print a new line also but in Write method it will just print something. No new line will be printed here.

For an example if we write in the main method Console.Write(“Hello World ”); then the output should be as follows-

Hello World press any key to continue

The line “press any key to continue” indicates that the program is terminated. Instead of this method if we use Console.WriteLine(“Hello World ”); then the output should be as follows-

Hello World

press any key to continue

Here we can see that the line “press any key to continue” is in a new line. So the method Writeline prints a new line after writing something to the console.

Similarly there are to methods for reading something in the console, one is Read and the other is ReadLine. The Read method read integer type from the console and the Readline method read string type from the console. So if we write Console.ReadLine() then we have to store the returned result in a string type variable so that we can use it later in the program.

Now let’s see the code our sample program. It is as follows-

using System;
class Program
{
   static void Main()
    {
        Console.WriteLine("What is your name?");
        string name = Console.ReadLine();
        Console.WriteLine("Welcome "+ name);
    }
}

Here we can see in the MAIN method first we are printing a message asking the user’s name. Then when our next line of code executed it waits for the user input that is our read operation from the console. When the user enters something and press the Enter button then Console.Readline methos reads what is entered in the console and return it as a string type. Here we store the returned string in a string type variable named name. So what user entered in the console now stored in the variable. Then in the next line we write in the console “Welcome “concatenated with the name of the user. Here we are concatenating two string- One is “Welcome ” and the other is string type variable called name with the “+” sign in the WriteLine method.
There are actually two ways of writing something in the console. They are-
• Concatenation
• Place holder syntax
We already have seen the concatenation method of writing something to the console. Now we will see the place holder syntax in the same program. If we want to use place holder syntax in the same program then the code should be as follows-

using System;
class Program
{
   static void Main()
    {
        Console.WriteLine("What is your name?");
        string name = Console.ReadLine();
        Console.WriteLine("Welcome {0}",name);
    }
}

Here we can see in case of “+” operator we use “{0}” in the string with Welcome. This is called the place holder. When we run the program, the value of the variables that we pass after comma in the WriteLine method replaces the place holder. So if we run this piece of code we will see the same result here.
The place holder syntax is more preferable than the Concatenation process. To see how place holder syntax gives more capability let’s modify the above program. Now we will ask the user to enter his/her first name then after reading the first name we will ask for last name and after reading that we will print the first name and last name separated by a comma with the welcome message. To do that the program should be as follows –

using System;
class Program
{
   static void Main()
    {
        Console.WriteLine("What is your first name?");
        string firstname = Console.ReadLine();
        Console.WriteLine("What is your last name?");
        string lastname = Console.ReadLine();
        Console.WriteLine("Welcome {0},{1}",firstname,lastname);
    }
}

Here in the code we can see there are two place holders and there are two string type variable as well to store the first name and last name of user. When we write the welcome message in WriteLine method we use two placeholder and two variable to replace the place holder. In the same way we can use as many as place holders we required. We just have to surround the number of that place holder with curly braces. That’s why place holder syntax is more preferable than the concatenation method.

Introduction(Understand the basic structure of a c# program)

Hello Everyone!! In this series of tutorial we are going to discuss about the basic elements of C#. Like all others OOP (Object Oriented Programming) languages C# is also an OOP language that means the three qualities that make a programming language object oriented can be found in C# also. The qualities are-

  • Encapsulation
  • Polymorphism
  • Inheritance

We will understand each of this qualities in the later session of this series. In this article we will understand the basic structure of a C# program. All the sample programs of this series is going to be a Console Application and we are using Visual Studio as the IDE. So first we will learn how to open a console application in Visual Studio.

A console application is nothing but a program that can be executed in the command prompt of our Computer. To open a console application first we have to open visual studio then from the menu choose File-> New-> Project. Then another windows will pop up then in the popup window choose Visual C# in the left and you can see console application there. Choose Console Application template and give it a suitable name, you can choose the location where to save this program in your pc from here also. When you choose everything click the OK button to create the program.

OpenNewProject

When you click the OK button the program will be created and you will see the following code –

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace introduction
{
    class Program
    {
        static void Main()
        {
        }
    }
}

Now for simplicity we will remove some code from the above and make it a very basic structure of a C# program. After removing those code the above program will looks like the following-

using System;

class Program
{
    static void Main()
    {

    }
}

The above program can be said as a very basic structure of C# program. Now we will describe each line of the above program.
The first line is-
using System;

This is called the namespace declaration. A namespace is nothing but a collection of some classes, enums, structs, interfaces and delegates. What are all these we will discuss later. A namespace can hold another namespace also. For now to understand the above line we can say there are some built-in methods in this namespace called System and to use those methods and classes we have to declare the namespace by using keyword at the top. Just for an example if we want to print something in the console then we can write the following code-

using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("Hello world");
    }
}

To run the above code press Ctrl+F5. Then the command prompt should appear with the message “Hello world”.
The definition of this Writeline method is written in the namespace called System. Now if we remove the using System; line from our code then we will get an error in the line Console.WriteLine(“Hello world”);
Because now the definition of WRITELINE method is missing from our program. If we want to remove the namespace declaration then we have to write the name in the line when we use a method belongs to that namespace as follows-

class Program
{
    static void Main()
    {
        System.Console.WriteLine("Hello world");
    }
}

Namespace is used to organize our code more effectively. If you don’t use the namespace declaration at the top then each time when you use a method you have to write its namespace which is more time consuming. So the use of namespace declaration is important.
Now the next thing in our basic structure is a Class declaration. We assume that you are familiar with OOP and if you are so then you are already known to class. Like other OOP language the class declaration in C# is exactly same. Anything you write in C# is belongs to a class. There are different types of class in C#. We will discuss it later in this series. Just for now we can say any piece of code should be inside of a class. Here the name of our class is Program.
Then there is also a method named Main and it is a static method. What is static method and class we will discuss it later. Now what we have to understand is the Main method is the starting point of our program. When we run our code it start to execute each line from the beginning of Main method and end when the Main method ends. To prove this, we can declare another same method named Main2 and in this method we print another message to differentiate the two method. We can consider the following piece of code-

using System;
class Program
{
    static void Main2()
    {
        Console.WriteLine("Another Message");
    }
    static void Main()
    {
        Console.WriteLine("Hello world");
    }
}

Here if we run the program we will see that only the message “Hello world” is printed. Another method named MAIN2 is not executed. So it’s proved that our program start from Main method and terminate when the MAIN method terminates. If we want to print the 2nd message then we have to call the MAIN2 method from MAIN method before it terminates. We can do it by the following-

using System;
class Program
{
    static void Main2()
    {
        Console.WriteLine("Another Message");
    }
    static void Main()
    {
        Console.WriteLine("Hello world");
        Main2();
    }
}

Now we should be able to see both messages.
In this article we see the basic structure of a C# programming and we can sum up with the following decisions from the above discussion-
• The namespace declaration using System; indicates that you are using System namespace
• A namespace is a collection of Classes, Structs, Delegates, Enums, Interfaces and used to organize the code more effectively.
• Our program starts with the Main method and terminates when the Main method terminates.