What is the difference between the is and as operators in C#?
C# is a class-oriented programming language mainly used for backend development. The is and as keywords are operators in C# that are noticeably different than each other.
Key differences
The following table represents the main differences between the two operators:
is | as |
Used only for reference, boxing, and unboxing conversions. | Used only for null-able reference, boxing conversions. |
Boolean return type. | Object/null return type. |
Checks the type of an object with the given type. | Converts an object to a given type if its type is compatible with the given type. |
Returns TRUE/FALSE based on the check. | Returns object or null based on the check. |
Examples
Let's take a look at these significant differences via code:
The is operator
Let's look at an example of the is operator:
using System;class HelloWorld{public class obj{}public class obj2:obj{}public class obj3{}static void Main(){//For built-in types//string msg = "Hello world!";Console.WriteLine(msg is string);Console.WriteLine(msg is char);Console.WriteLine(msg is int);Console.WriteLine(msg is double);//For user-defined typesobj class1 = new obj2();Console.WriteLine(class1 is obj);Console.WriteLine(class1 is obj2);Console.WriteLine(class1 is obj3);}}
Explanation
Lines 4–6: We create three classes
obj,obj2, andobj3.obj2is a derived class ofobj, whileobj3is a separate non-related class.Lines 11–18: We represent how the
isoperator works for built-in types. The comparison with thestringclass returns True as the match was correct, while the comparison with the other classes(char,int,double) returns False as there was a type unmatch.Lines 21–27: After the declaration of the
objobject(class1), we check it againstobj,obj2, andobj3types using theisoperator. Forobjandobj2, it returns True asobjis the same type ofclass1object andobj2is a derived class ofobj. Since there is a mismatch in types forobj3, we print false.
The as operator
Let's look at an example of the as operator:
using System;class HelloWorld{public class temp{}static void Main(){object[] array = new object[7];array[0] = 1;array[1] = "Hello world!";array[2] = 'H';array[3] = 2.3;array[4] = new temp();array[5] = null;array[6] = "Hi!";for(int i = 0; i < 7; i++){var check = array[i] as string;if(check != null){Console.WriteLine(check);}else{Console.WriteLine("Null!");}}}}
Explanation
Line 4: We declare a custom type named
tempclass.Lines 7–14: We define an
objectarray with values of different data types.Lines 16–24: A loop traverses the entire
arrayand has a check that prints Null if thecheckvariable does not have a string type. We print the contained string incheckif theasmatch is correct with the current object of the array.
Free Resources