What's the Difference between the Is and As operator in C#

Category: C SharpWhat's the Difference between the Is and As operator in C#
Editor">Editor Staff asked 2 years ago

What’s the Difference between the Is and As operator in C#

1 Answers
Editor">Editor Staff answered 2 years ago

“is” operator

 
In C# language, we use the “is” operator to check the object type. If two objects are of the same type, it returns true, else it returns false.
 
Let’s understand this in our C# code. We declare two classes, Speaker and Author.

 

  1. class Speaker {    
  2.     public string Name {    
  3.         get;    
  4.         set;    
  5.     }    
  6. }    
  7. class Author {    
  8.     public string Name {    
  9.         get;    
  10.         set;    
  11.     }    
  12. }    

Now, let’s create an object of type Speaker:

 

  1. var speaker = new Speaker { Name=“Gaurav Kumar Arora”};    

Now, let’s check if the object is Speaker type:

 

  1. var isTrue = speaker is Speaker;     

In the preceding, we are 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 are 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 speaker is not an object of Author type.
 
“as” operator
 
The “as” operator behaves in a similar way as the “is” operator. The only difference is it returns the object if both are compatible with that type. Else it returns a null.
 
Let’s understand this in our C# code.

 

  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 a dynamic object and returns the object name property if the object is of the Author type. 
 
Here, we’ve 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. Console.WriteLine(“Author name is:{0}”, authorName);    

It returns an empty string:

 

  1. authorName = GetAuthorName(speaker);     
  2. Console.WriteLine(“Author name is:{0}”, authorName);