Difference between is and as keyword

C#Casting

C# Problem Overview


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

C# Solutions


Solution 1 - C#

###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.

Solution 2 - C#

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;

Solution 3 - C#

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.

Solution 4 - C#

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)
{
     ...
}

Solution 5 - C#

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.

Solution 6 - C#

I would say: read MSDN online, but here it is:

The is operator checks whether an object is compatible with a given type, and the result of the evaluation is a Boolean: true or false.

The as operator will never throw an exception.

Solution 7 - C#

Is operator , a cast, returns true if it succeeds. It returns false if the cast fails. With it, you cannot capture the converted variable. This operator is most useful when checking types in if-statements and expressions.The is-cast is only ideal if the resulting variable will not be needed for further use

As is a cast. With it, we gain performance and avoid exceptions when a cast is invalid. Null is returned when the cast is impossible. For reference types, the as-cast is recommended. It is both fast and safe.We can test the resulting variable against null and then use it. This eliminates extra casts

Solution 8 - C#

  1. is operator checks whether the object is compatible with the given type the result based upon true or false.
  2. as is used to cast one type to another type and on conversion failure results null except then raising exception. well see link for better understanding with examples https://blogs.msdn.microsoft.com/prakasht/2013/04/23/difference-between-direct-casting-is-and-as-operator-in-c/

Solution 9 - C#

The As operator is similar to a cast, but returns null instead of an exception if it fails.

And the Is operator is used to check if one object is compatible with a certain type. It's usually used in If statements.

Solution 10 - C#

is: The is operator is used to check whether the run-time type of an object is compatible with a given type

as: The as operator is used to perform conversions between compatible types.

object s = "this is a test";
string str=string.Empty;
if( s is string)
    str = s as string;

Solution 11 - C#

Have a look at the below youtube video which explains the difference in a more demonstrative and visual way :-

https://www.youtube.com/watch?v=IKmRtJcRX_I

Below goes the long answer with code explanation.

“IS” keyword is useful to check if objects are compatible with a type. For instance in the below code we are checking if “ocust” object is a type of “Customer” class.

object ocust = new Customer();

if (ocust is Customer)
{ 

“AS” keyword helps to do conversion from one type to other type. For instance in the below code we are converting object to a string data type. If the “AS” keyword is not able to type cast it returns NULL.

object o = "somestring";
string str = o as string;

Solution 12 - C#

Both operator are used for safe type casting.

AS Operator :

The AS operator also checks whether the type of a given object is compatible with the new object type. This keyword will check whether the type of a given object is compatible with the new object type. If it's not compatible with the new one then it will return NULL.

IS Operator:

This Operator checks whether the type of an object is compatible with the new object. If it's compatible it returns true otherwise false.

Solution 13 - C#

MyClass myObject = (MyClass) obj;

vs

MyClass myObject = obj as MyClass;

The second will return null if obj isn't a MyClass, rather than throw a class cast exception.

is will only return true or false

Solution 14 - C#

Both IS and AS are used for Safe Type Casting

IS Keyword--> checks whether the type of an given object is compatible with the new object type. It Never Throws an exception. This is a Boolean type..returns either true or false

`student stud = new student(){}
if(stud is student){} // It returns true // let say boys as derived class
if(stud is boys){}// It returns false since stud is not boys type
 //this returns true when,
student stud = new boys() // this return true for both if conditions.`

AS Keyword: checks whether the type of an given object is compatible with the new object type. It returns non-null if given object is compatible with new one, else null.. This throws an exception.

`student stud = new student(){}
 // let say boys as derived class
boys boy = stud as boys;//this returns null since we cant convert stud type from base class to derived class
student stud = new boys()
boys boy = stud as boys;// this returns not null since the obj is pointing to derived class`

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAmanView Question on Stackoverflow
Solution 1 - C#GuffaView Answer on Stackoverflow
Solution 2 - C#Prem Ranjan JhaView Answer on Stackoverflow
Solution 3 - C#Abhilash NKView Answer on Stackoverflow
Solution 4 - C#ShdNxView Answer on Stackoverflow
Solution 5 - C#Faizan ButtView Answer on Stackoverflow
Solution 6 - C#Patrick PetersView Answer on Stackoverflow
Solution 7 - C#Pankaj IkharView Answer on Stackoverflow
Solution 8 - C#azhar abbasiView Answer on Stackoverflow
Solution 9 - C#HarryView Answer on Stackoverflow
Solution 10 - C#KMånView Answer on Stackoverflow
Solution 11 - C#Shivprasad KoiralaView Answer on Stackoverflow
Solution 12 - C#TukaramView Answer on Stackoverflow
Solution 13 - C#vzadesView Answer on Stackoverflow
Solution 14 - C#Sandeep ReddyView Answer on Stackoverflow