I’m sure that for all of us there have been times when we want to get the type of an object that we’re using, especially when dealing with abstract classes,
interfaces, and inheritance. For this, there’s a right way and a wrong way to do things.
The first way to determine the type of an object instance is to use Reflection. You may have heard that reflection causes significant overhead. This is no exception. Here’s an example.
public void Display(IList displayer)
{
if (displayer.GetType() == Type.GetType("System.Collections.ArrayList"))
{
return;
}
}
It’s bad enough that we’re using reflection for this information (via the GetType()
method of
displayer
), but also that we’re hard-coding
the type of the class we’re interested in with “System.Collections.ArrayList
.” This can be cleaned up to the following:
public void Display(IList displayer)
{
if (displayer.GetType() == typeof(System.Collections.ArrayList))
{
return;
}
}
However, it’s still reflection. Instead of using this, consider using the
is
keyword, which in fact does not use reflection
at all but a special MSIL statement which is pretty quick, as far as what I’ve heard.
public void Display(IList displayer)
{
if (displayer is System.Collections.ArrayList)
{
return;
}
}
Another keyword that is often overlooked is the as
keyword. This handles casting on reference types. Although I hope you haven’t,
maybe you’ve seen something like this before:
DataSet ds;
try
{
ds = (DataSet)Request.Cache["ds"];
}
catch { }
You don’t even need a try/catch statement here; just use the as keyword! Not only will it handle times when it is impossible to cast
to the requested type by setting the value to null, but it also uses the same MSIL instruction as
is
, so it’s pretty efficient. You can’t use
these two keywords with value types because value types and reference types are handled differently in memory.
Here’s one last example:
public void Display(IList«IDisposable» list)
{
int count = list.Count;
for (int i = 0; i < count; ++i)
{
IDisposable item = list[i];
if (item is SqlConnection)
{
(item as SqlConnection).Open();
}
}
}
Say you wanted to check if a particular item is a SqlConnection
object, and if it is, open it. Remember how
is
and as
do basically the exact same thing though? So in this previous block of code you have a double cast. Consider doing something like the following:
public void Display(IList«IDisposable» list)
{
int count = list.Count;
for (int i = 0; i < count; ++i)
{
IDisposable item = list[i];
SqlConnection cnn = item as SqlConnection;
if (cnn != null)
{
cnn.Open();
}
}
}