IS And AS Keyword Difference In C#

Introduction

 
In this blog, we are going to discuss IS and AS keyword differences.
 
Let's demonstrate the IS keyword. Please check the below code snippet.
  1. class Program  
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.   
  6.         object str1 = "Madan";  
  7.         if(str1 is string)  
  8.         {  
  9.             Console.WriteLine("yes it is a number");  
  10.             Console.ReadLine();  
  11.         }  
  12.   
  13.     }  
  14. }  
Is keyword is useful when we want to check if the variables are the same type or not. Please check the below snapshot for output.
 
IS And AS Keyword Difference In C# 
 
Let's demonstrate the AS keyword. Please check the below code snippet.
  1. class Program  
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.   
  6.         object str1 = "Madan";  
  7.         string str2 = str1 as string;  
  8.         Console.WriteLine(str2);  
  9.         Console.ReadLine();  
  10.   
  11.    }  
  12. }  
In the above code, str1 is an object and we are converting an object to a string. As keyword is helpful when we want to convert an object from one type to another type. If the  AS keyword failed to convert one type to another type it will set null value. Please check the snapshot for the above program output.
 
IS And AS Keyword Difference In C# 
 
Key points to remember,
  • IS keyword is helpful to check if the object is that type or not 
  • AS keyword is helpful too if we want to convert one type to another type.  
  • IS keyword type is boolean and AS keyword is not a boolean type.
  • The is operator returns true if the given object is of the same type whereas as operator returns the object when they are compatible with the given type.

Summary

 
In this blog we discussed about the IS and AS keyword with simple programs.