Saturday, May 5, 2018

C# : Difference between is and as operator in C#

"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 {  
  3.         get;  
  4.         set;  
  5.     }  
  6. }  
  7. class Author {  
  8.     public string Name {  
  9.         get;  
  10.         set;  
  11.     }  
  12. }  
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. Console.WriteLine("Author name is:{0}", authorName);   
It returns an empty string:
  1. authorName = GetAuthorName(speaker);   
  2. Console.WriteLine("Author name is:{0}", authorName);   

No comments:

Post a Comment