130

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

Venkat
  • 2,549
  • 2
  • 28
  • 61
Aman
  • 1,445
  • 2
  • 13
  • 11
  • 7
    Is is as or is as is? http://blogs.msdn.com/b/ericlippert/archive/2010/09/16/is-is-as-or-is-as-is.aspx – LukeH Sep 24 '10 at 11:09
  • 3
    If you're interested in this subject you probably also want to know what the difference is between "as" and "cast" operators: http://blogs.msdn.com/b/ericlippert/archive/2009/10/08/what-s-the-difference-between-as-and-cast-operators.aspx – Eric Lippert Sep 24 '10 at 15:26
  • @EricLippert That link is now broken. – Max Barraclough Sep 22 '20 at 08:13
  • 1
    @MaxBarraclough: Thanks for the note; Microsoft has several times now moved my blog archive without making forwarding links. I've made a copy of the original article in the first comment here: https://ericlippert.com/2010/09/16/is-is-as-or-is-as-is/. I'll post a link to the second in a later comment. – Eric Lippert Sep 22 '20 at 15:50
  • @MaxBarraclough: Updated link for the second one is: https://ericlippert.com/2009/10/08/whats-the-difference-between-as-and-cast-operators/ -- thanks again. – Eric Lippert Sep 23 '20 at 17:35

13 Answers13

162

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.
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • Consider adding remark about checks for value types need to use `is` (as they can't use `as` - `var v = someInt as int;` (see http://stackoverflow.com/questions/31013690/is-there-ever-a-reason-to-use-is-versus-as) – Alexei Levenkov Jun 23 '15 at 21:33
  • 5
    This isn't correct. `is` doesn't check if an object can be cast to a specific type. An integer casts to a long fine but `10 is long` is false. – Martin Smith Aug 02 '16 at 20:35
  • 13
    @MartinSmith: You are mixing up type conversion with casting. An integer can be converted to long, but it can not be casted to long because it is not a long. – Guffa Aug 23 '16 at 11:04
  • 3
    You're telling me that an integer can't be cast to a long? That `(long)some_integer` will fail? I'm pretty sure we both know that isn't true without even running it so please explain what you mean. – Martin Smith Aug 23 '16 at 19:03
  • 16
    @MartinSmith: You are still confusing casting with conversion. You are not casting an integer to a long, you are converting an integer to a long. Although they use the same syntax, references are casted and values are converted. – Guffa Aug 27 '16 at 13:19
  • 2
    Note **about `is`**: "_Note that the **is** operator only considers reference conversions, boxing conversions, and unboxing conversions. Other conversions, such as user-defined conversions, are not considered._"(msdn.microsoft.com/en-us/library/scekt9xw.aspx). **About `as`**: "_Note that the **as** operator performs only reference conversions, nullable conversions, and boxing conversions. The as operator can't perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions._" (https://msdn.microsoft.com/en-us/library/cscsdfbt.aspx) – user1234567 Dec 27 '16 at 11:55
  • 1
    @Guffa Martin Smith most definitely was casting an integer to a long. Words have meanings. You cannot just make up what "cast" means. A cast is nothing more or less than an explicit conversion. Source: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/casting-and-type-conversions Explicit example from that page: `double x = 1234.7;` `int a;` `// Cast double to int.` `a = (int)x;` –  Jan 12 '18 at 12:52
36

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;
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Prem Ranjan Jha
  • 459
  • 6
  • 3
  • 1
    The equivalence clearly shows which of the two is more primitive and underlies their relationship elegantly! Thanks for the equivalence! – Musa Al-hassy Jul 01 '15 at 21:08
  • 2
    @MusaAl-hassy Actually this does not show which is more primitive. `is` can be expressed with `as` and `as` can be expressed with `is`. Here is how to make a `is` with the `as` keyword. `Bool b = obj is Student;` is equivalent to: `Bool b = (obj as Student) != null;` More on this [here](https://blogs.msdn.microsoft.com/ericlippert/2010/09/16/is-is-as-or-is-as-is/) – Alex Telon Jul 14 '17 at 17:48
11

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.

Ola Ström
  • 4,136
  • 5
  • 22
  • 41
Abhilash NK
  • 501
  • 5
  • 5
6

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)
{
     ...
}
ShdNx
  • 3,172
  • 5
  • 40
  • 47
4

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.

Faizan Butt
  • 261
  • 1
  • 3
  • 14
3

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.

Patrick Peters
  • 9,456
  • 7
  • 57
  • 106
2

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

2
  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/
1

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.

Dov Miller
  • 1,958
  • 5
  • 34
  • 46
Tukaram
  • 66
  • 6
1

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.

Harry
  • 3,076
  • 4
  • 28
  • 44
1

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;
KMån
  • 9,896
  • 2
  • 31
  • 41
  • 3
    Your answer is correct, but your sample code is an anti-pattern. It's expensive to do `is` then `as`: it unboxes twice. For reference types, you should just do `as`, then check for null to see if it worked. – Steven Sudit Sep 24 '10 at 11:14
1
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

vzades
  • 112
  • 2
  • 4
1

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`