Discussing: is and as operators of C# Language

Discussing: is and as operators of C# Language

Today, we are going to discuss is and as operators if C# language.

Whenever we think about type casting abd want to avoid type mismatch exception or other type exceptions, ‘as’ and ‘is’ keywords are come into picture.
Also, we can use these operators to check object compatability.

‘is’ operator

  • In C# language, we use ‘is’ operator to check the object type. If object is of same type,
    it returns true and false if not.

Lets understand above from a small program:

We defined two classes:

 class Speaker
    { public string Name { get; set; } }
 class Author
    { public string Name { get; set; } }

Now, lets try to check above types as:

var speaker = new Speaker { Name="Gaurav Kumar Arora"};

We declared an object of Speaker

var isTrue = speaker is Speaker;

above, we are just checking the matching type. Yes, our speaker is an object of Speaker type,

Console.WriteLine("speaker is of Speaker type:{0}", isTrue);

so, it results as 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 our speaker is not an object of Author type.

‘as’ operator

  • It behaves similar to ‘is’ operator. The only difference it returns the object if both are compatible
    to that type else it returns null.

Lets understand above with a small snippet:

 public static string GetAuthorName(dynamic obj)
        {
            Author authorObj = obj as Author;
            return (authorObj != null) ? authorObj.Name : string.Empty;
        }

We have a method, which accepts dynamic objects and returns object name property if object is of Author type.

Here, we declared two objects:

var speaker = new Speaker { Name="Gaurav Kumar Arora"};
var author = new Author { Name = "Gaurav Kumar Arora" };

Following returns ‘Name’ property:

var authorName = GetAuthorName(author);

Console.WriteLine("Author name is:{0}", authorName);

It returns empty string:

authorName = GetAuthorName(speaker);

Console.WriteLine("Author name is:{0}", authorName);

Conclusion

In this article, we get an idea about ‘as’ and ‘is’ operators of C# language.

1 comment on “Discussing: is and as operators of C# Language”

Leave A Reply