"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:
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:
- class Speaker {
- public string Name {
- get;
- set;
- }
- }
- class Author {
- public string Name {
- get;
- set;
- }
- }
- var speaker = new Speaker { Name="Gaurav Kumar Arora"};
- var isTrue = speaker is Speaker;
- Console.WriteLine("speaker is of Speaker type:{0}", isTrue);
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);
"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.
- public static string GetAuthorName(dynamic obj)
- {
- Author authorObj = obj as Author;
- return (authorObj != null) ? authorObj.Name : string.Empty;
- }
Here, we declared two objects:
- var speaker = new Speaker { Name="Gaurav Kumar Arora"};
- var author = new Author { Name = "Gaurav Kumar Arora" };
- var authorName = GetAuthorName(author);
- Console.WriteLine("Author name is:{0}", authorName);
- authorName = GetAuthorName(speaker);
- Console.WriteLine("Author name is:{0}", authorName);
No comments:
Post a Comment