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.
class Program
{
static void Main(string[] args)
{
object str1 = "Madan";
if (str1 is string)
{
Console.WriteLine("yes it is a number");
Console.ReadLine();
}
}
}
Is the keyword useful when we want to check if the variables are the same type or not? Please check the below snapshot for output.
Let's demonstrate the AS keyword. Please check the below code snippet.
class Program
{
static void Main(string[] args)
{
object str1 = "Madan";
string str2 = str1 as string;
Console.WriteLine(str2);
Console.ReadLine();
}
}
In the above code, str1 is an object and we are converting an object to a string. A keyword is helpful when we want to convert an object from one type to another type. If the AS keyword fails to convert one type to another type it will set null value. Please check the snapshot for the above program output.
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 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 the IS and AS keywords with simple programs.