CodeAnalysis is my new friend

The other day I had a hassle with CodeAnalysis in my VS 2008 installation. The code below was, at least to me, very readable and correct but it showed up as the errors pointing to this code:

foreach (Control currentControl in this.Controls)
{
    if (currentControl is Panel)
    {
        foreach (Control childControl in (currentControl as Panel).Controls)
        {
            if (childControl is TextBox)
            {
                where = CreateTextBoxWhere((TextBox)childControl, where);
            }
            else if (childControl is DropDownList)
            {
                where = CreateDropDownListWhere((DropDownList)childControl, where);
            }
        }
    }
}

 

 

  • CA1800 : Microsoft.Performance : ‘currentControl’, a variable, is cast to type ‘Panel’ multiple times in method. Cache the result of the ‘as’ operator or direct cast in order to eliminate the redundant isint instruction.
  • CA1800 : Microsoft.Performance : ‘childControl’, a variable, is cast to type ‘TextBox’ multiple times in method. Cache the result of the ‘as’ operator or direct cast in order to eliminate the redundant castclass instruction.
  • CA1800 : Microsoft.Performance : ‘childControl’, a variable, is cast to type ‘DropDownList’ multiple times in method. Cache the result of the ‘as’ operator or direct cast in order to eliminate the redundant castclass instruction.

 

So, after a little looking around on the net and good help from a couple of colleagues I figured out that I did a lot of unnecessary casting with the IS operator so I rewrote the code as below and it didn’t´t complain.
I guess that CodeAnalysis is quite good to have sometimes.

The “improved” code:

foreach (Control currentControl in this.Controls)
{
    Panel panel = currentControl as Panel;
    
    if (panel != null)
    {
        foreach (Control childControl in panel.Controls)
        {
            TextBox textbox = childControl as TextBox;
            DropDownList dropdownlist = childControl as DropDownList;
            
            if (textbox != null)
            {
                where = CreateTextBoxWhere(textbox, where);
            }
            else if (dropdownlist != null)
            {
                where = CreateDropDownListWhere(dropdownlist, where);
            }
        }
    }
}

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: