"is" and "as" Operators of C#

Today, we will discuss the "is" and "as" operators in the C# language.
 
The "as" and "is" keywords are useful for avoiding type mismatch exceptions or other type exceptions when doing type casting.
 
Also, we can use these operators to check object compatibility.

"is" operator

In the C# language, we use the "is" operator to check the object type. If the two objects are of the same type, it returns true and false if not.
 
Let's understand the preceding from a small program.
 
We defined the following two classes:
  1. class Speaker  
  2.     { public string Name { getset; } }  
  1. class Author  
  2.     { public string Name { getset; } }  
Now, let's try to check the preceding types as:
  1. var speaker = new Speaker { Name="Gaurav Kumar Arora"};  
We declared an object of Speaker as in the following:
  1. var isTrue = speaker is Speaker;  
In the preceding, we are just checking the matching type. Yes, our speaker is an object of Speaker type.
  1. Console.WriteLine("speaker is of Speaker type:{0}", isTrue);  
So, the results as true.
 
But, here we get false:
  1. var author = new Author { Name = "Gaurav Kumar Arora" };  
  2. var isTrue = speaker is Author;  
  3. Console.WriteLine("speaker is of Author type:{0}", isTrue);  
Because our our speaker is not an object of Author type.

"as" operator

The "as" operator behaves similar to the "is" operator. The only difference is it returns the object if both are compatible to that type else it returns null.
 
Let's understand the preceding with a small snippet as in the following:
  1. public static string GetAuthorName(dynamic obj)  
  2. {  
  3. Author authorObj = obj as Author;  
  4. return (authorObj != null) ? authorObj.Name : string.Empty;  
  5. }  
We have a method that accepts dynamic objects and returns the object name property if the object is of the Author type.
 
Here, we declared two objects:
  1. var speaker = new Speaker { Name="Gaurav Kumar Arora"};  
  2. var author = new Author { Name = "Gaurav Kumar Arora" };  
The following returns the "Name" property:
  1. var authorName = GetAuthorName(author);  
  2.   
  3. Console.WriteLine("Author name is:{0}", authorName);  
It returns an empty string:
  1. authorName = GetAuthorName(speaker);  
  2.   
  3. Console.WriteLine("Author name is:{0}", authorName);  
Conclusion
 
This article provided the basics of the "as" and "is" operators of the C# language.

Up Next
    Ebook Download
    View all
    Learn
    View all