When to use “is” and when to use “as” in C#

The is operator accepts an object on the left hand side and a type on the right. It returns true if the run-time type of the object on the left is compatible with the type on the right. Always use is before making the type cast.
The as actually cast the type on the left to the type on the right, null will be returned if the conversion fails.

  1. as is preferred, because it is more efficient (the conversion is already done with the as operator.
  2. For value-type variables, like int, char you can only use is to convert from one type to another.

Leave a Reply

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