Difference between is and as keyword

is

The is operator checks if an object can be cast to a specific type.

Example:

if (someObject is StringBuilder) ...

as

The as operator attempts to cast an object to a specific type, and returns null if it fails.

Example:

StringBuilder b = someObject as StringBuilder;
if (b != null) ...

Also related:

Casting

The cast operator attempts to cast an object to a specific type, and throws an exeption if it fails.

Example:

StringBuilder b = (StringBuilder)someObject.

The Difference between IS and As is that..

IS - Is Operator is used to Check the Compatibility of an Object with a given Type and it returns the result as a Boolean (True Or False).

AS - As Operator is used for Casting of Object to a given Type or a Class.

Ex.

Student s = obj as Student;

is equivalent to:

Student s = obj is Student ? (Student)obj : (Student)null;

Both is and as keywords are used for type casting in C#.

When you take a look at the IL code of usages of both the keywords, you will get the difference easily.

C# Code:

BaseClass baseclassInstance = new DerivedClass();
DerivedClass derivedclassInstance;

if (baseclassInstance is DerivedClass)
{
   derivedclassInstance = (DerivedClass)baseclassInstance;
   // do something on derivedclassInstance
}


derivedclassInstance = baseclassInstance as DerivedClass;

if (derivedclassInstance != null)
{
   // do something on derivedclassInstance
}

IL code (for above C# code is in the attached image):

IL code for above C# code The IL code for is keyword usage contains IL instructions both isinsta and castclass.
But the IL code for as keyword usage has only isinsta.

In the above mentioned usage, two typecast will happen where is keyword is used and only one typecast where as keyword is used.

Note: If you are using is keyword to check some condition and do not have any interest in the typecast result, then there will be only one typecast, i.e.

if (baseclassInstance is DerivedClass)
{
   // do something based on the condition check.
}

is and as keywords will be used based on the necessity.


The is keyword checks whether the value on its left side is an instance of the type on the right side. For example:

if(obj is string)
{
     ...
}

Note that in this case you'll have to use an extra explicit cast to get obj as string.

The as keyword is used to cast nullable types. If the specified value is not an instance of the specified type, null is returned. For example:

string str = obj as string;
if(str != null)
{
     ...
}