There are two safe ways to check if an object is of the type you expect:
as
and
is
. The third way is to use a cast and see it it throws an exception, but that is a bad practice and should be avoided.
The difference is that
is
just check, and returns true or false, while
as
converts, and returns null if it isn't a type in the object inheritance.
So you can do it two ways:
if (obj is myType)
{
MyType mt = (MyTpe) obj;
...
}
Or
MyType mt = obj as MyType;
if (mt != null)
{
...
}
I prefer the second as it includes an explicit null check.
We can use this in common routines, for example a Click event handler that could come from a variety of sources:
private void button1_Click(object sender, EventArgs e)
{
Button b = sender as Button;
if (b != null)
{
...
}
}
If it isn't a button, then we may not know what to do with it!