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.
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. |
Let's take a look at these significant differences via code:
is
operatorLet'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);}}
Lines 4–6: We create three classes obj
, obj2
, and obj3
. obj2
is a derived class of obj
, while obj3
is a separate non-related class.
Lines 11–18: We represent how the is
operator works for built-in types. The comparison with the string
class 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 obj
object(class1
), we check it against obj
, obj2
, and obj3
types using the is
operator. For obj
and obj2
, it returns True as obj
is the same type of class1
object and obj2
is a derived class of obj
. Since there is a mismatch in types for obj3
, we print false.
as
operatorLet'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!");}}}}
Line 4: We declare a custom type named temp
class.
Lines 7–14: We define an object
array with values of different data types.
Lines 16–24: A loop traverses the entire array
and has a check that prints Null if the check
variable does not have a string type. We print the contained string in check
if the as
match is correct with the current object of the array.
Free Resources