try
{
DataGridItem d = (DataGridItem)obj.Parent;
if (d.GetType() == “DataGridItem”)
{
// Do something with d
}
}
catch (InvalidCastException e)
{
…
}
Using “as”
DataGridItem d = obj.Parent as DataGridItem;
if (null != d)
{
// Do something with d
}
Using the example for the “as” operator, consider this statement:
DataGridItem d = obj.Parent as DataGridItem;
if (d is DataGridItem)
{
// Do something with d
}
The difference, as you probably noticed, is that in the “as” example d is compared for inequality against null, whereas in the “is” example it was compared against the type in question. Using “is” is more intuitive, more readable, and slightly more efficient, making it by far the better choice.
Using “is” and “as” result in fewer lines of IL and fewer lines of actual C# code by avoiding a lot of extraneous checks and statements,