is and as Operator in C#
Introduction
Look at the example given below,
Circle c = new Circle(32);
object o = c;
int i = (int)o; // it compiles okay but throws an exception at runtime
Here runtime is more suspicious, if the type of object in memory does not match the cast, the runtime will throw an InvalidCastException. We should be prepared to catch this exception and handle it appropriately if it occurs. However, catching an exception and attempting to recover in the event that the type of an object is not what we expected it to be is a rather cumbersome approach. C# provides two more very useful operators that can help us to perform casting in a much more elegant manner by using is and as operators. Let's have some talk on is and as operators too.
is Operator
is operator is used to check whether the run-time type of an object is compatible with a given type or not. In other word, we use is operator to verify that the type of an object is what we expect it to be. Let's look its syntax:
expression is type
Example of is Operator
using System;
class Class1
{
}
class Class2
{
}
public class IsTest
{
public static void Test(object o)
{
Class1 a;
Class2 b;
if (o is Class1)
{
Console.WriteLine("o is Class1");
a = (Class1)o;
}
else if (o is Class2)
{
Console.WriteLine("o is Class2");
b = (Class2)o;
}
else
{
Console.WriteLine("o is neither Class1 nor Class2.");
}
}
public static void Main()
{
Class1 c1 = new Class1();
Class2 c2 = new Class2();
Test(c1);
Test(c2);
Test("Passing String Value instead of class");
Console.ReadKey();
}
}
In above example, I'll be checking object o is class or not. If passed argument is not class then application will jump to message 'o is neither class1 nor class2'.
as Operator
as Operator is used to perform conversions between compatible types. Actually, as operator fulfills a similar role like is but in a slightly truncated manner. Let's look its syntax:
expression as type
Example of is Operator:
using System;
class Class1
{
}
class Class2
{
}
public class IsTest
{
public static void Main()
{
object[] myObjects = new object[6];
myObjects[0] = new Class1();
myObjects[1] = new Class2();
myObjects[2] = "string";
myObjects[3] = 32;
myObjects[4] = null;
for (int i = 0; i < myObjects.Length; ++i)
{
string s = myObjects[i] as string;
Console.Write("{0}:", i);
if (s != null)
Console.WriteLine("'" + s + "'");
else
Console.WriteLine("not a string");
}
Console.ReadKey();
}
}
In above example, each and every value is being casted into string by using as operator and assigning it to s string variable which comes at console.
So, that's all about the is and as Operators. Thanks for joining this article.
Comments
Post a Comment