Does the is operator indicate whether or not an object is an instance of a certain class, or only if it can be casted to that class?
Assume I have a DbCommand called command that has actually has been initialized as a SqlCommand. What is the result of command is OracleCommand?
(SqlCommand and OracleCommand both inherit from DbCommand)
It checks if the object is a member of that type, or a type that inherits from or implements the base type or interface. In a way, it does check if the object can be cast to said type.
command is OracleCommandreturns false as it’s anSqlCommand, not anOracleCommand. However, bothcommand is SqlCommandandcommand is DbCommandwill return true as it is a member of both of those types and can therefore be downcast or upcast to either respectively.If you have three levels of inheritance, e.g.
BaseClass,SubClassandSubSubClass, an object initialized asnew SubClass()only returns true foris BaseClassandis SubClass. AlthoughSubSubClassderives from both of these, the object itself is not an instance of it, sois SubSubClassreturns false.