The 'is' operator is used to check whether the run-time type of an object is compatible with a given type, and is a "reference type". This is very handy when you have code somewhere in a business or data layer and you cannot figure out why an exception is occuring.
For example:
public static void RunThis()
{
// For this example the following obj is a class already created
object obj = new MyClass();
CastCheck(obj);
}
public static void CastCheck(object obj)
{
// For this example the following classes are already created
Class1 a;
Class2 b;
if (obj is Class1)
{
Console.WriteLine("obj is Class1");
a = (Class1)obj; // do something with a
}
else if (obj is Class2)
{
Console.WriteLine("v is Class2");
b = (Class2)obj; // do something with b
}
else
{
Console.WriteLine("obj is neither Class1 nor Class2.");
}
}
The 'is' operator only considers reference conversions, boxing conversions, and unboxing conversions. Other conversions, such as user-defined conversions, are not considered by the is operator.
aa01e2db-916a-47ec-bcf9-5a2faf80e9f4|0|.0