The Checked and Unchecked Operator
C# provides special operators, checked and unchecked. It enforces CLR to check overflow.
Consider the following code
- class Program
- {
- static void Main(string[] args)
- {
- byte b = 255;
-
- b++;
-
- Console.WriteLine(b);
- Console.ReadKey();
- }
- }
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.
- class Program
- {
- static void Main(string[] args)
- {
- byte b = 255;
- checked
- {
- b++;
- }
- Console.WriteLine(b);
- Console.ReadKey();
- }
- }
When we try to run this code, we will get an error.
Unchecked is the default behavior it will produce 0 as out put,
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
- namespace ConsoleApplication2
- {
- class Program
- {
- static void Main(string[] args)
- {
- int i = 10;
- if(i is string)
- {
- Console.WriteLine("string type");
-
- }
- else if (i is float )
- {
- Console.WriteLine("float type");
- }
- else if(i is int)
- {
- Console.WriteLine("Int type");
- }
- Console.ReadKey();
- }
- }
- }
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.
- namespace ConsoleApplication2
- {
- class Program
- {
- static void Main(string[] args)
- {
- object o1 = "C# corner ";
- object o2 = 5;
- string s1=o1 as string;
- string s2 = o2 as string;
- Console.WriteLine(s1);
- Console.WriteLine(s2);
- Console.ReadKey();
- }
- }
- }