By Yuvaraj Shanmugam

Is and As operators in C#

Both ‘is’ and ‘as’ operators are used for type casting. But there are significant differences in these keywords

Is Operator

The Is operator is used to check the type during runtime. It is a boolean operator and returns true if the given object is of the same type .

The above is an example of Is operator which will display True in console

The Is operator will return False if the given object is not same type.

In the above example the type conversion will happen in runtime and if conversion is True it will assign to the variable

As Operator

The As operator will do explicit cast and will assign null if type cast is unsuccessful.

In the above example when an object of string type is tried to cast to integer, it will return null.

With the examples above we can see that the is operator is used for boxing and unboxing conversions whereas as operator is used for nullable, reference and boxing conversions.

I hope you had something useful to learn, please leave your comments below.

One thought on “Is and As operators in C#”

Leave a Reply

Your email address will not be published. Required fields are marked *