is

suggest change

Checks if an object is compatible with a given type, i.e. if an object is an instance of the BaseInterface type, or a type that derives from BaseInterface:

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 {}
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(); //prefered method since you incur only one unboxing penalty
}

But, from C# 7 pattern matching feature extends the is operator to check for a type and declare a new variable at the same time. Same code part with C# 7 :

if (d is BaseClass asD ){
    asD.Method();
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Keywords:
* as
* goto
* break
* const
* for
* is
* fixed
* sealed
* typeof
* this
* void
* char
* params
* base
* string
* null
* return
* while
* using
* ulong
* uint
* unsafe
* int
* var
* lock
* where
* extern
* switch
* when
* struct
* static
* do
* bool
* long
* sizeof
* in
* enum
* ushort
* sbyte
* event

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
51 Keywords
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script