theycallmemorty
theycallmemorty

Reputation: 12962

C# 'is' operator Clarification

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)

Upvotes: 9

Views: 353

Answers (6)

Lars Tackmann
Lars Tackmann

Reputation: 20865

if(something is X) checks if the underlying type of something is X. This is significantly different from checking if a type supports casting to X since many types can support casts to X without being of type X.

Conversely the as operator attempts a conversion to a particular type and assigns null if source type is not within the inheritance chain of the target type.

Upvotes: 0

BoltClock
BoltClock

Reputation: 723729

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.

Upvotes: 18

Ben Straub
Ben Straub

Reputation: 5776

From MSDN:

An is expression evaluates to true if [...] expression can be cast to type

Upvotes: 4

user47589
user47589

Reputation:

http://msdn.microsoft.com/en-us/library/scekt9xw%28v=vs.80%29.aspx

An is expression evaluates to true if the provided expression is non-null, and the provided object can be cast to the provided type without causing an exception to be thrown.

Upvotes: 3

Randolpho
Randolpho

Reputation: 56391

An is expression evaluates to true if the provided expression is non-null, and the provided object can be cast to the provided type without causing an exception to be thrown.

Source

Upvotes: 6

Doug
Doug

Reputation: 6442

is indicate if the object can be casted to a class or interface.

If you have a BaseClass and a SubClass then:

var obj = new SubClass();

obj is SubClass returns true;

obj is BaseClass also returns true;

Upvotes: 1

Related Questions