Difference between is and as keyword

Viewed 97619

Please tell what is the difference between is and as keyword in C#

14 Answers

is OPERATOR The is operator in C# is used to check the object type and it returns a bool value: true if the object is the same type and false if not. or also The “is” operator is used to check whether the run-time type of an object is compatible with a given type or not. For null objects, it returns false e.g

if(obj is AnimalObject)
{
 //Then Work
}

as OPERATOR

The as operator does the same job of is operator but the difference is instead of bool, it returns the object if they are compatible to that type, else it returns null.In otherwords, The ‘as‘ operator is used to perform conversions between compatible types.

e.g

Type obj = Object as Type;

Advantages of as over is In case of is operator, to type cast, we need to do two steps:

Check the Type using is
If it’s true then Type cast

Actually this affects the performance since each and every time the CLR will go through the inheritance hierarchy, checking each base type against the specified type.

To avoid this, use as, it will do it in one step. Only for checking the type should we use the is operator.

Related