'is' And 'as' Keywords In C#

In this blog, I am going to share with you about 'as' and 'is' keywords in C#.
 
Introduction
 
'as' and 'is' are the keywords used for conversion/TypeCasting in C#. I hope you have the basic understanding of casting/TypeCasting in C#. If not, don't worry. Just visit the link below to have a clear understanding of it.
Why should we use 'as' keyword?
 
Let's understand the below program to know why we should use the 'as' keyword.
  1. using System;  
  2.   
  3. namespace Tutpoint  
  4. {  
  5.     class Program  
  6.     {  
  7.         class Tutpoint  
  8.         {  
  9.             public Tutpoint()  
  10.             {  
  11.                 Console.WriteLine("Hello TutPoint");  
  12.             }  
  13.         }  
  14.         static void Main(string[] args)  
  15.         {  
  16.             // Creating object of object type  
  17.             object obj = new object();  
  18.             Console.WriteLine(obj);  
  19.   
  20.             // This will raise a runtime InvalidCastException as "Unable to cast object of type 'System.Object' to type 'Tutpoint'"  
  21.             Tutpoint tutpoint = (Tutpoint)obj;  
  22.             if (tutpoint != null)  
  23.             {  
  24.                 Console.WriteLine("tutpoint does not contain null value");  
  25.             }  
  26.             else  
  27.             {  
  28.                 Console.WriteLine("tutpoint contains null value");  
  29.             }  
  30.             Console.ReadKey();  
  31.         }  
  32.     }  
  33. }  
In this program, inside 'Main' method, first, we created an object 'obj' of the object type. Then, what we did is casting 'obj' of type object to 'TutPoint' type. This casting is incompatible and raises a runtime exception as "Unable to cast object of type 'System.Object' to type 'Tutpoint'".
 
So, in order to avoid runtime exceptions, the 'as' keyword is used. If the casting is incompatible, then it will return a null value instead of an exception. This is very useful in saving our program from crashes/exceptions.
 
What is 'as' Keyword?
  1. 'as' is a keyword used for conversion from one type to another. The type can be a reference or nullable.
  2. 'as' keyword checks the compatibility of one object type with another object type. In case of compatible, it will return the value of the new object type otherwise, null will be returned.
  3. If the conversion from one type to another type fails, then it will return a null value instead of raising an exception. So, the return value can be null also.

    Syntax of 'as' keyword
    1. Expression as dataType;
  4. We cannot perform conversion of value types (int, double, char, bool) and user-defined types.
  5. The return type should be the reference or nullable type. Since the returned value can be null and as we know value types cannot contain null, value types cannot be used.
  6. 'as' improves the performance and it is safe for casting.
The above program can be rewritten using 'as' keyword.
  1. using System;  
  2.   
  3. namespace Tutpoint  
  4. {  
  5.     class Program  
  6.     {  
  7.         class Tutpoint  
  8.         {  
  9.             public Tutpoint()  
  10.             {  
  11.                 Console.WriteLine("Hello TutPoint");  
  12.             }  
  13.         }  
  14.         static void Main(string[] args)  
  15.         {  
  16.             // Creating object of object type  
  17.             object obj = new object();  
  18.             Console.WriteLine(obj);  
  19.   
  20.             // 'as' keyword used to convert 'obj' of type 'object' to 'Tutpoint' type  
  21.             // It will return null as the conversion of object type to Tutpoint is incompatible  
  22.             Tutpoint tutpoint = obj as Tutpoint;  
  23.             if (tutpoint != null)  
  24.             {  
  25.                 Console.WriteLine("tutpoint does not contain null value");  
  26.             }  
  27.             else  
  28.             {  
  29.                 Console.WriteLine("tutpoint contains null value");  
  30.             }  
  31.   
  32.   
  33.             Console.ReadKey();  
  34.         }  
  35.     }  
  36. }  
Output
  1. System.Object  
  2. tutpoint contains null value  
Another example.
  1. using System;  
  2.   
  3. namespace Tutpoint  
  4. {  
  5.     class Program  
  6.     {  
  7.         class Tutpoint  
  8.         {  
  9.   
  10.             public string Name { getset; }  
  11.         }  
  12.   
  13.         class Tutlover  
  14.         {  
  15.             public string Name { getset; }  
  16.         }  
  17.   
  18.         static void Main(string[] args)  
  19.         {  
  20.             //Creating object of classes 'Tutpoint' and 'Tutlover'  
  21.             Tutpoint tutpoint = new Tutpoint();  
  22.             Tutlover tutlover = new Tutlover();  
  23.   
  24.             //Creating array of objects  
  25.             object[] object_array = new object[7];  
  26.             object_array[0] = tutpoint;  
  27.             object_array[1] = tutlover;  
  28.             object_array[2] = "hey..Folks";  
  29.             object_array[3] = 1000;  
  30.             object_array[4] = 1.212;  
  31.             object_array[5] = 'c';  
  32.             object_array[6] = true;  
  33.   
  34.             for (int i = 0; i < 7; i++)  
  35.             {  
  36.                 // as-casting of obj_array[i] value to string. If compatible then return the value else return null  
  37.                 string str = object_array[i] as string;  
  38.                 if (str != null)  
  39.                 {  
  40.                     Console.WriteLine(str);  
  41.                 }  
  42.                 else  
  43.                 {  
  44.                     Console.WriteLine("Null value");  
  45.                 }  
  46.             }  
  47.             Console.WriteLine();  
  48.   
  49.             for (int i = 0; i < 6; i++)  
  50.             {  
  51.                 // as-casting of obj_array[i] value to Tutlover type. If compatible then return the value else return null  
  52.                 Tutlover obj = object_array[i] as Tutlover;  
  53.                 if (obj != null)  
  54.                 {  
  55.                     Console.WriteLine(obj);  
  56.                 }  
  57.                 else  
  58.                 {  
  59.                     Console.WriteLine("Null value");  
  60.                 }  
  61.             }  
  62.             Console.WriteLine();  
  63.   
  64.             for (int i = 0; i < 6; i++)  
  65.             {  
  66.                 // as-casting of obj_array[i] value to object. If compatible then return the value else return null  
  67.                 object obj = object_array[i] as object;  
  68.                 if (obj != null)  
  69.                 {  
  70.                     Console.WriteLine(obj);  
  71.                 }  
  72.                 else  
  73.                 {  
  74.                     Console.WriteLine("Null value");  
  75.                 }  
  76.             }  
  77.             Console.ReadKey();  
  78.         }  
  79.     }  
  80. }  
Output:
  1. Null value  
  2. Null value  
  3. hey..Folks  
  4. Null value  
  5. Null value  
  6. Null value  
  7. Null value  
  8.   
  9. Null value  
  10. Tutpoint.Program+Tutlover  
  11. Null value  
  12. Null value  
  13. Null value  
  14. Null value  
  15.   
  16. Tutpoint.Program+Tutpoint  
  17. Tutpoint.Program+Tutlover  
  18. hey..Folks  
  19. 1000  
  20. 1.212  
  21. c  
In the above program, we created an array of objects and assigned different values to it. After that, we cast it using 'as' keyword to string, Tutlover class type, object type respectively.
 
When we cast it with string,
  1. string str = object_array[i] as string;  
Then, it will return the string value only when object_array[i] value is of 'string' type, else return null.
 
When we cast it with Tutlover class type,
  1. Tutlover str = object_array[i] as Tutlover;  
Then, it will return the value of 'Tutlover' type only when object_array[i] value is of 'Tutlover' type, else return null.
 
When we cast it with object class type,
  1. object str = object_array[i] as object;  
Then, it will return value of any type.
Now, what if we cast it with int, bool, double, char??
  1. int int_value = object_array[i] as int;  
  2. char char_value = object_array[i] as char;  
  3. double double_value = object_array[i] as double;  
  4. bool bool_value = object_array[i] as bool;  
The compiler will generate an error as "The as operator must be used with a reference type or nullable type ('type' is a non-nullable value type)"
 
What is 'is' keyword?
 
1) 'is' keyword checks whether the conversion from one object type to another object type is compatible or not.
2) It returns true if the conversion is compatible, else returns false.
3) The syntax of 'is' keyword is,
  1. Boolean result = object_type_to is object_type_From;  
Here, 'object_type_to' is the object type which is to be check with object type 'object_type_From'. 'result' is the variable of bool type.
 
4) 'is' evaluates compatibility at runtime.
5) 'is' keyword can also check compatibility of value types (int, double, char, bool) and user-defined types.
  1. using System;  
  2.   
  3. namespace Tutpoint  
  4. {  
  5.     class Program  
  6.     {  
  7.         class Tutpoint  
  8.         {  
  9.   
  10.             public string Name { getset; }  
  11.         }  
  12.   
  13.         class Tutlover  
  14.         {  
  15.             public string Name { getset; }  
  16.         }  
  17.   
  18.         static void Main(string[] args)  
  19.         { //Creating object of classes 'Tutpoint' and 'Tutlover'  
  20.             Tutpoint tutpoint = new Tutpoint();  
  21.             Tutlover tutlover = new Tutlover();  
  22.   
  23.             //Creating array of objects  
  24.             object[] object_array = new object[7];  
  25.             object_array[0] = tutpoint;  
  26.             object_array[1] = tutlover;  
  27.             object_array[2] = "hey..Folks";  
  28.             object_array[3] = 1000;  
  29.             object_array[4] = 1.212;  
  30.             object_array[5] = 'c';  
  31.             object_array[6] = true;  
  32.   
  33.             for (int i = 0; i < 7; i++)  
  34.             {  
  35.                 // 'is' will check whether obj_array[i] value is compatible with string type. If compatible then return true else return false  
  36.                 Boolean result = object_array[i] is string;  
  37.                 if (result)  
  38.                 {  
  39.                     Console.WriteLine("True value");  
  40.                     // Write the statements which are to be executed when result will be true  
  41.                 }  
  42.                 else  
  43.                 {  
  44.                     Console.WriteLine("False value");  
  45.                     // Write the statements which are to be executed when result will be true  
  46.                 }  
  47.             }  
  48.             Console.WriteLine();  
  49.   
  50.             for (int i = 0; i < 7; i++)  
  51.             {  
  52.                 // 'is' will check whether obj_array[i] value is compatible with object type. If compatible then return true else return false  
  53.                 Boolean result = object_array[i] is object;  
  54.                 if (result)  
  55.                 {  
  56.                     Console.WriteLine("True value");  
  57.                     // Write the statements which are to be executed when result will be true  
  58.                 }  
  59.                 else  
  60.                 {  
  61.                     Console.WriteLine("False value");  
  62.                     // Write the statements which are to be executed when result will be true  
  63.                 }  
  64.             }  
  65.             Console.WriteLine();  
  66.   
  67.             for (int i = 0; i < 7; i++)  
  68.             {  
  69.                 // 'is' will check whether obj_array[i] value is compatible with Tutlover type. If compatible then return true else return false  
  70.                 Boolean result = object_array[i] is Tutlover;  
  71.                 if (result)  
  72.                 {  
  73.                     Console.WriteLine("True value");  
  74.                     // Write the statements which are to be executed when result will be true  
  75.                 }  
  76.                 else  
  77.                 {  
  78.                     Console.WriteLine("False value");  
  79.                     // Write the statements which are to be executed when result will be true  
  80.                 }  
  81.             }  
  82.             Console.WriteLine();  
  83.             Console.ReadKey();  
  84.         }  
  85.     }  
  86. }  
Output
  1. False value  
  2. False value  
  3. True value  
  4. False value  
  5. False value  
  6. False value  
  7. False value  
  8.   
  9. True value  
  10. True value  
  11. True value  
  12. True value  
  13. True value  
  14. True value  
  15. True value  
  16.   
  17. False value  
  18. True value  
  19. False value  
  20. False value  
  21. False value  
  22. False value  
  23. False value  
Conclusion
 
'as' and 'is' are used for casting. The 'is' keyword is one of the best approached to typecast but it has some limitations also. With 'as' keyword, we either get the converted value of another type or null while with 'is' keyword, we either get true or false. On the basis of the value, we execute the statements. I hope this article helps you to understand a bit more about 'is' and 'as' keywords.
 
Thank you and feel free to ask any question or make a suggestion.
Ebook Download
View all
Learn
View all