Differentiate between is and as operator in C#

is operator

The is operator allows us to check whether an object is compatible with a specific type. Here the phrase "is compatible" means that an object is either of that type or is derived from that type.

For eg:

int k = 0;
if (k is object)
Console.WriteLine("i is an object");

as operator

The as operator is used to perform explicit type conversion of reference type. If the type being converted is compatible with the specified type, then that conversion is successful else as operator will return a null value.

For eg:

object x = "I am here";
object y = 10;

string s1 = x as string; // here conversion is compatible so,s1="I am Here"
string s2 = y as string; // here conversion is incompatible so,s2=null

No comments:

Post a Comment