“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.
- class Speaker {
- public string Name {
- get;
- set;
- }
- }
- class Author {
- public string Name {
- get;
- set;
- }
- }
Now, let’s create an object of type Speaker:
- var speaker = new Speaker { Name=“Gaurav Kumar Arora”};
Now, let’s check if the object is Speaker type:
- var isTrue = speaker is Speaker;
In the preceding, we are checking the matching type. Yes, our speaker is an object of Speaker type.
- Console.WriteLine(“speaker is of Speaker type:{0}”, isTrue);
So, the results are true.
But, here we get false:
- var author = new Author { Name = “Gaurav Kumar Arora” };
- var isTrue = speaker is Author;
- 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.
- public static string GetAuthorName(dynamic obj)
- {
- Author authorObj = obj as Author;
- return (authorObj != null) ? authorObj.Name : string.Empty;
- }
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:
- var speaker = new Speaker { Name=“Gaurav Kumar Arora”};
- var author = new Author { Name = “Gaurav Kumar Arora” };
The following returns the “Name” property:
- var authorName = GetAuthorName(author);
- Console.WriteLine(“Author name is:{0}”, authorName);
It returns an empty string:
- authorName = GetAuthorName(speaker);
- Console.WriteLine(“Author name is:{0}”, authorName);