C# 'is' operator Clarification

前端 未结 6 1853
半阙折子戏
半阙折子戏 2021-01-17 21:11

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

6条回答
  •  清歌不尽
    2021-01-17 21:22

    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 OracleCommand returns false as it's an SqlCommand, not an OracleCommand. However, both command is SqlCommand and command is DbCommand will 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, SubClass and SubSubClass, an object initialized as new SubClass() only returns true for is BaseClass and is SubClass. Although SubSubClass derives from both of these, the object itself is not an instance of it, so is SubSubClass returns false.

提交回复
热议问题