Prerequisite: is Keyword and as Keyword
Before implementing is operation without is keyword, let us have a brief outlook on how is keyword actually works.
In C# is keyword is used to evaluate compatibility at runtime. It determines whether an object instance or the result of an expression can be converted to a specified type.
expr is type
Example: In the below code class Program class inherits a class c1 and in “if condition” the compatibility is checked using is operator which returns true.
Is implementation without using is keyword
The similar functionality can be implemented using as keyword which returns
- null if the compatibility is not set
- and in case of compatible operands, it returns the LHS operand.
Example: In the below code, the object of c1 class is pro2 and thus cannot be assigned as an instance of Program class thus obj2 is set as null which later on is checked in if condition.
Note: You can also find some significant differences between the is keyword and as keyword by going through the article Is vs As operator keyword in C#