Casting can be performed in a much better way with the use of is and as operators. Using these operators there wont be any invalidcastexception. So you can get ride of the logic of catching and handling this exception.
Using Is Operator
Is operator can be used to check whether an object is of a particular type. Is
operator returns boolean value.
if(obj is string)
{
}
Here in the above example, if the obj is of type string then the is operator returns true else false. And inside the if condition the casting can be performed.
if(obj is string)
{
string str = (string)obj;
}
Below is a complete example code which explains the working of is operator.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Examples
{
class EndUser
{
static void Main(string[] args)
{
Developer d = new Developer();
Tester t = new Tester();
SeniorDeveloper sd = new SeniorDeveloper();
CastObject(d);
CastObject(t);
CastObject(sd);
Console.ReadLine();
}
static void CastObject(object obj)
{
Developer dev;
Tester testr;
// Check the type of object using is operator and then cast
if (obj is Developer)
{
dev = (Developer)obj;
Console.WriteLine("This is a Developer Object");
}
else if(obj is Tester)
{
testr = (Tester)obj;
Console.WriteLine("This is a Tester Object");
}
}
}
class Developer
{
}
class Tester
{
}
class SeniorDeveloper : Developer
{
}
}
Using As operator
As operator does the work of verifying the type and casting together at a time
compared to is operator.
string str = obj as string.
if(str!=null)
{}
Here in the example an object obj is casted to string. If the obj is of different type and cannot be casted then as operator returns null. So just verify whether str is null or not to confirm whether the casting is successful or not.
Below is a complete example code which explains the working of as operator.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CastingUsingAs
{
class Program
{
static void Main(string[] args)
{
object[] objects = new object[4];
objects[0] = new Developer();
objects[1] = new Tester();
objects[2] = new SeniorDeveloper();
objects[3] = "Hello";
CastObject(objects);
Console.ReadLine();
}
static void CastObject(object[] objects)
{
foreach (object obj in objects)
{
Developer d = obj as Developer;
if (d != null)
{
Console.WriteLine("Is a developer object");
}
else
{
Console.WriteLine("Is not a developer object");
}
}
}
}
class Developer
{
}
class Tester
{
}
class SeniorDeveloper : Developer
{
}
}
Conclusion:
Is operator can be used in places where we need to check only if an object is of any particular type. And for casting purpose As operator could be chosen over is operator since it does the work of checking the type and casting together.
No comments:
Post a Comment