Checks whether an object's type is the given type, derives from it, or implements it:
interface BaseInterface {}
class BaseClass : BaseInterface {}
class DerivedClass : BaseClass {}
var d = new DerivedClass();
Console.WriteLine(d is DerivedClass); // True
Console.WriteLine(d is BaseClass); // True
Console.WriteLine(d is BaseInterface); // True
Console.WriteLine(d is object); // True
Console.WriteLine(d is string); // False
var b = new BaseClass();
Console.WriteLine(b is DerivedClass); // False
Console.WriteLine(b is BaseClass); // True
Console.WriteLine(b is BaseInterface); // True
Console.WriteLine(b is object); // True
Console.WriteLine(b is string); // False
If the intent of the cast is to use the object, it is best practice to use the as keyword:
interface BaseInterface {}
class BaseClass : BaseInterface
{
public void Method() {}
}
class DerivedClass : BaseClass {}
var d = new DerivedClass();
Console.WriteLine(d is DerivedClass); // True - valid use of 'is'
Console.WriteLine(d is BaseClass); // True - valid use of 'is'
if(d is BaseClass){
var castedD = (BaseClass)d;
castedD.Method(); // valid, but not best practice
}
var asD = d as BaseClass;
if (asD!=null) {
asD.Method(); // preferred: the type is tested once. This is not unboxing; the object is a reference type
}
From C# 7, pattern matching extends the is operator so it can test the type and declare a variable at the same time. The same check in C# 7:
if (d is BaseClass asD ){
asD.Method();
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents