The is operator is a binary operator that is used to check whether a value is compatible with a given type. Its left operand is a value and right operand is a type.
More precisely, the left operand is an expression which can be of value type or of reference type. The expr is T asks: "Can the runtime value stored in expr be treated as type T?" If yes then "expr is T" returns true and If no then "expr is T" returns false. But the "expr" is not converted into type T. No object is changed, no conversion happens. The "expr" can be any value e.g. integer literal, string literal, integer variable, float variable, reference variable etc.
Suppose that Bird is derived class of Animal class.
Animal animal = new Bird();
Here animal variable type is Animal at compile time. This reference variable can point to Animal type objects and its subtypes(Bird) objects. At the runtime, it is decided whether animal is pointing to Animal object or Bird object. The actual runtime object is Bird created using new operator. Then: if (animal is Bird) returns true.
Suppose that Snake is an independent class from Animal class.
Animal animal = new Snake();
Here animal variable type is Animal at compile time. This reference variable can point to Animal type objects and its subtypes(Bird) objects but not any independent Snake type object. The compiler will throw error at compile time with message: "Cannot implicitly convert type 'Snake' to 'Animal' ". The code: Animal animal = new Snake(); will not compile.
In case of code: Animal animal = new Bird(); we can write the following code:
if (animal is Bird)
{
Console.WriteLine("At runtime, animal refers to an object of Bird type.");
}
At runtime, animal variable refers to the object of Bird type, created using new operator.
From the above discussion, it is obvious that is operator is used to check the compatibility of expression with a given type at Runtime. The is operator is a Boolean operator. If expression is compatible with a given type at Runtime, it returns True, else False. Secondly, the expression is not converted into any type becuase of is operator. Only the reference variable type may change at runtime; it may start pointing to the type given as right operand of the is operator.
Summary
- The is operator is a binary operator.
- The is operator is a Boolean operator.
- The is operator is used to check the compatibility of expression with a given type at Runtime.
- The expression as left operand is not converted into the type given as right operand becuase of is operator.
- If type compatibility is successful, type cast can be done thereafter without any fear of runtime exception: InvalidCastException.
No comments:
Post a Comment