What is Dead code?
It can be unreachable code, redundant code, and/or unused code. Using the Code Analysis feature of Visual Studio we can find it.
Why to remove dead code
The following are possible reasons to remove dead code:
- Sometimes we waste a lot of time thinking why a breakpoint does not hit a method/class.
- To increase the code coverage result.
- Code maintainability.
- Improve performance.
What those rules are
The following are the rules:
- Private methods that are not called from any other code (CA1811)
- Unused local variables (CA1804)
- Unused private fields (CA1823)
- Unused parameters (CA1801)
- Internal classes that are not instantiated from any other code (CA1812).
Demo
You can create a new rule set file via "File" –> "New" –> "File". In this example, I've given the rule set the name DeadCodeDetectionRules.ruleset
Since the rule set doesn't contain any rules yet, the rule set editor shows none of the rules as being checked. The rule set editor (shown below) is a new window in Visual Studio Team System 2010 that allows you manage rules and rule sets.
To start adding rules to the DeadCodeDetectionRules rule set, you can search for a rule using either the rule number or its name, as shown below. You can also simply expand the rule categories and select the rules that you are interested in.
After adding all five dead code detection rules, the rule set editor should look something like this:
Applying a rule set to a project
Once the rule set has been created, the next step is to apply the rule set to a project. This can be done via the Project Properties window. On the Code Analysis tab, click the dropdown next to the "[Open]" button and select "Browse..." to browse to the location of the rule set file.
So now, all the dead code detection rules are part of a single rule set that make it much easier to manage.
Happy Coding.