#225 – Free Static Analysis Using FxCop

Although code analysis can be extremely helpful, it’s available in only the Premium and Ultimate editions of Visual Studio 2010.  If you don’t have access to one of these editions but still want to be able to do some sort of static analysis, you can use the (free) FxCop tool.  FxCop used to be distributed separately, but is now part of the Windows SDK.

FxCop works by doing static analysis of your assemblies and looking for violations of programming and design rules.

Start by downloading and installing the Windows SDK.  After the install, you’ll see FxCop in your Start Menu.

After you start up FxCop, select Project | Add Targets and select the .dll or .exe file that you want to analyze.  Then click the Analyze button.

When analysis completes, you’ll see a list of messages indicating suggested changes.

#224 – One Example of a Problem that Code Analysis Would Catch

As an example of the type of issues that code analysis would catch, consider the following piece of code.

        static void Main()
        {
            Console.WriteLine("Grande schmande, just give me some coffee..");
        }

This code obviously works fine–it just prints out a string.  But if we want to someday localize this program, we’ll want to be reading the string from a resource file, rather than hard-coding it like this.  So when we build the project with code analysis turned on, we see the following warning:

CA1303: Do not pass literals as localized parameters

An externally visible method passes a string literal as a parameter to a constructor or method in the .NET Framework class library, and that string should be localizable.

We see this warning in the Error List window when we build the project.

#223 – Enabling Code Analysis for Your Project

If you’re using Visual Studio 2010, the Ultimate and Premium versions come with a built-in code analysis tool, which allows you to check your code for potential problems.  Code analysis will check your code at the time that you build it, looking for logic errors or common mistakes.

To turn code analysis on at build-time, do the following.  Right-click your project in the Solution Explorer and select Properties.

Click on the Code Analysis tab.

Check the box labeled Enable Code Analysis on Build.

The next time that you build your project, the code analysis tool will check it for the problems covered by the Microsoft Basic Correctness Rules rule set.  Any problems found will be reported as Warnings in the Error List window.