Is vs As operator keyword in C#
The difference between is and as operators are as follows:
- The is operator is used to check if the run-time type of an object is compatible with the given type or not whereas as operator is used to perform conversion between compatible reference types or Nullable types.
- The is operator is of boolean type whereas as operator is not of boolean type.
- The is operator returns true if the given object is of the same type whereas as operator returns the object when they are compatible with the given type.
- The is operator returns false if the given object is not of the same type whereas as operator return null if the conversion is not possible.
- The is operator is used for only reference, boxing, and unboxing conversions whereas as operator is used only for nullable, reference and boxing conversions
Example of is operator:
using System;
public class P { }
public class P1 : P { }
public class P2 { }
public class GFG {
public static void Main()
{
P o1 = new P();
P1 o2 = new P1();
Console.WriteLine(o1 is P);
Console.WriteLine(o1 is Object);
Console.WriteLine(o2 is P1);
Console.WriteLine(o2 is Object);
Console.WriteLine(o2 is P1);
Console.WriteLine(o1 is P2);
Console.WriteLine(o2 is P2);
}
}
|
Output:
True
True
True
True
True
False
False
Example of as operator:
using System;
class Y { }
class Z { }
class GFG {
static void Main()
{
object [] o = new object [5];
o[0] = new Y();
o[1] = new Z();
o[2] = "Hello" ;
o[3] = 4759.0;
o[4] = null ;
for ( int q = 0; q < o.Length; ++q) {
string str1 = o[q] as string ;
Console.Write( "{0}:" , q);
if (str1 != null ) {
Console.WriteLine( "'" + str1 + "'" );
}
else {
Console.WriteLine( "Is is not a string" );
}
}
}
}
|
Output:
0:Is is not a string
1:Is is not a string
2:'Hello'
3:Is is not a string
4:Is is not a string
Last Updated :
21 Jan, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...