Some Special Operators in C#

The Checked and Unchecked Operator

C# provides special operators, checked and unchecked. It enforces CLR to check overflow. 

Consider the following code

  1. class Program  
  2.     {  
  3.         static void Main(string[] args)  
  4.         {  
  5.             byte b = 255;  
  6.               
  7.                 b++;  
  8.              
  9.             Console.WriteLine(b);  
  10.             Console.ReadKey();  
  11.         }  
  12.     }  
output

Byte data type range is 0 to 255 and in this code when we try to increase value then it loses value and it produces 0 as output. We have to find out any method through which we can get the exact value.

To do this we used checked operator. Consider the following code.

code
  1. class Program  
  2.     {  
  3.         static void Main(string[] args)  
  4.         {  
  5.             byte b = 255;  
  6.             checked  
  7.             {  
  8.                 b++;  
  9.             }  
  10.             Console.WriteLine(b);  
  11.             Console.ReadKey();  
  12.         }  
  13.     }  
When we try to run this code, we will get an error.

Unchecked is the default behavior it will produce 0 as out put,
  1. unchecked  
  2. {  
  3. b++;  
  4. }  
The is Operator

With the help of “is” operator we can check if an object is compatible with a specific type. The is operator returns a Boolean value of true or false.

Consider following code
  1. namespace ConsoleApplication2  
  2. {  
  3.     class Program  
  4.     {  
  5.         static void Main(string[] args)  
  6.         {  
  7.             int i = 10;  
  8.             if(i is string)  
  9.             {  
  10.                 Console.WriteLine("string type");  
  11.   
  12.             }  
  13.             else if (i is float )  
  14.             {  
  15.                 Console.WriteLine("float type");  
  16.             }  
  17.             else if(i is int)  
  18.             {  
  19.                 Console.WriteLine("Int type");  
  20.             }  
  21.             Console.ReadKey();  
  22.         }  
  23.     }  
  24. }  
It will produce “Int type” as output

The as Operator

It is used to perform explicit type conversion of reference type.

If type converted is compatible with specified type then conversion is performed successfully otherwise it assigns null value. For example conceder the following code.
  1. namespace ConsoleApplication2  
  2. {  
  3.     class Program  
  4.     {  
  5.         static void Main(string[] args)  
  6.         {  
  7.             object o1 = "C# corner ";  
  8.             object o2 = 5;  
  9.                 string s1=o1 as string;  
  10.                 string s2 = o2 as string;  
  11.                 Console.WriteLine(s1);  
  12.                 Console.WriteLine(s2);  
  13.             Console.ReadKey();  
  14.         }  
  15.     }  
  16. }   

 

Ebook Download
View all
Learn
View all