In the development of the software, typecasting is an inescapable thing. In many cases, one needs to convert an object(Type) into another object(Type) and sometimes got InvalidCastException. So, to overcome such types of exception C# provides is operator.
The is operator is used to check if the run-time type of an object is compatible with the given type or not. It returns true if the given object is of the same type otherwise, return false. It also returns false for null objects.
expression is type
Here, the expression will be evaluated to an instance of some type. And type is the name of the type to that the result of the expression is to be converted. If the expression is not null and the object results from evaluating the expression can be converted to the specified type then is operator will return true otherwise it will return false.
Example 1: In the below code, we have three classes i.e. Author, Work and GFG. GFG is the driver class which contains the Main method. Class ‘Author’ and ‘Work’ have data members and method. In the Main method, objects of class Author and Work created and methods of these classes are called using the instance of the class. After that, a bool value bool result; is taken to store the return value of is operator. The line of code i.e. result = a is Author; is used to check whether a(object of class author) is of type Author. It will return true as a is the instance of Author class. But instance w is not of type Author, that’s why it returns false. After that, we are assigning null to object a which will give result false as comparing to an instance of Author.
Is a is Author? : True Is w is Author? : False Is a is Author? : False
Example 2: In the below program, we are checking whether the derived type is of the expression type on the left-hand side of the is operator. If is derived then it will return true otherwise it returns false.
True True True True True False False
- Only reference, boxing, and unboxing conversions are considered by the is operator keyword.
- User-defined conversions or the conversion which are defined using the implicit and explicit are not considered consider by is operator. For the conversions which are known at the compile-time or handled by an implicit operator, is operator will give warnings for that.