Click here to Skip to main content
15,892,575 members
Articles / Programming Languages / C#
Tip/Trick

As, Is, and Reflection

Rate me:
Please Sign up or sign in to vote.
3.50/5 (2 votes)
11 Jun 2012CPOL2 min read 11.3K   6   3
Difference and simple implementation of as, is, and Reflection.

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.

C#
public void Display(IList displayer)
{
    if (displayer.GetType() == Type.GetType("System.Collections.ArrayList"))
    {
        return;
    }
    // Other processing...
}

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:

C#
public void Display(IList displayer)
{
    if (displayer.GetType() == typeof(System.Collections.ArrayList))
    {
        return;
    }
// Other processing...
}

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.

C#
public void Display(IList displayer)
{
    if (displayer is System.Collections.ArrayList)
    {
        return;
    }
    // Other processing...
}

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:

C#
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:

C#
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();
        }
        // Other processing...
    }
}

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:

C#
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();
        }
        // Other processing...
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Question[My vote of 2] My vote of 2 Pin
imak19-Aug-12 11:42
imak19-Aug-12 11:42 
GeneralMy vote of 5 Pin
johannesnestler13-Jun-12 3:56
johannesnestler13-Jun-12 3:56 
GeneralThoughts Pin
PIEBALDconsult8-Jun-12 7:33
mvePIEBALDconsult8-Jun-12 7:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.