Static Code Analysis - Part 1 - Setting Up To Run
I've created a small sample application to help with this post. Basically, it’s a class library application called CalculatorExample. I've added one class so far, called MyCalculator. This class has two methods: Add(num1, num2) and Subtract(num1, num2). I actually used the Class Designer to build the class and methods.
I want to run Static Code Analysis against this sample app. In the Solution Explorer, right-click on the project name (CalculatorExample) and select Properties. This opens the properties page for the project. Click the Code Analysis tab on the left-hand side to open the Code Analysis section. To have static code analysis run every time the application is built, you need to check the Enable Code Analysis (defines CODE_ANALYSIS constant) checkbox.
You can also decide which rules you want to use when static code analysis is run. The rules are grouped into different groups, such as Design Rules and Globalization Rules. You can check/uncheck entire groups, or you can drill down into a group and disable or enable individual rules, depending on your process.
Finally, for each rule and/or rule group, you can specify what happens when the rule is broken. You can choose to have Visual Studio throw either a warning or an error. Simple double-click the Status column for a rule or rule group to toggle between error and warning. By default, all the rules are set to throw warnings.
Once you have everything configured, save your changes to the project properties and close them. For my example, I left all the rules checked. The following image shows you the Code Analysis tab for my project properties.