Avoid using the is keyword in C#
The C# language has the is
keyword which allows you to check if a variable is of a given type.
if(myVar is MyClass)
This is commonly helpful when dealing with a variable of type object
, checking if a type extends a base class, checking if a type implements an interface or when dealing with generics. It is often seen inside of events to check the type of the sender
object:
public void button1_Click(object sender, EventArgs e)
{
if(sender is DropDownList)
{
// Do stuff!
}
}
Although useful, I would really advise not using is
and instead use as
. The as
keyword is a defensive cast, which means that a cast will be attempted and if the object is not able to be casted to the supplied type null
is returned instead.
DataTable dt = sender as DataTable;
if(dt != null)
{
// Do stuff... WITH a DataTable!
}
else
{
// sender isn't a DataTable
}
The reason I’d advise against using is
is because is
actually will cause you to perform 2 casts – one to check if the object is of the type and then a second to actually capture the casted value.
if(sender is DataTable)
{
DataTable dt = sender as DataTable; // Second cast. Uh oh!
}
Using as
(or an explicit cast, for that matter) only performs a single cast:
DataTable dt = sender as DataTable;
if(dt != null)
{
// We now have a DataTable and can table our data!
}
else
{
// Try another defensive cast perhaps?
}
The performance difference is really negligible and for all intents and purposes it really doesn’t matter which one you use when thinking of performance. But in the interest of separation of concerns, as-then-null
checks separate the statements better – a cast followed by a null check. Using is-then-cast
performs a type check then attempts to convert the value a second time. It’s inconsistent, and in code, consistency is king.