views:

151

answers:

2

I have a VS.NET 2008 project. Is it possible to check for classes that are not used anywere in the project? With FXcop I can find unused variables and unused code, but not unused classes.

+1  A: 

Resharper (with solution-wide checking on) automatically notified you of unused classes in your project & solution

thecoop
Didnt know about the solution-wide checking, thanks
Ivo
Only works from > 4.5.
Carra
+1  A: 

The tool NDepend can help you to find unused code in any .NET code base. You can edit the following 3 Code query Language (CQL) queries to detect unused methods, fields and classes. These 3 queries can be customized to your exact need. Notice also how these queries are prefixed with WARN IF Count > 0 IN, that transform them from CQL queries to CQL rules. These CQL rules can be checked in your CI environment, or even, interactively in VS itself while you are coding:

// <Name>Potentially unused methods</Name>
WARN IF Count > 0 IN SELECT METHODS WHERE
  MethodCa == 0 AND            // Ca=0 -> No Afferent Coupling -> The method is not used in the context of this application.
  !IsPublic AND                // Public methods might be used by client applications of your assemblies.
  !IsEntryPoint AND            // Main() method is not used by-design.
  !IsExplicitInterfaceImpl AND // The IL code never explicitely calls explicit interface methods implementation.
  !IsClassConstructor AND      // The IL code never explicitely calls class constructors.
  !IsFinalizer AND             // The IL code never explicitely calls finalizers.
  !IsVirtual AND
  !IsEventAdder AND
  !IsEventRemover 

// <Name>Potentially unused types</Name>
WARN IF Count > 0 IN SELECT TYPES WHERE  
 TypeCa == 0 AND // Ca=0 -> No Afferent Coupling -> The type
                 // is not used in the context of this application.
 !IsPublic  AND  // Public types might be used by client applications of
                 // your assemblies.   
 !NameIs "Program" 

// <Name>Potentially unused fields</Name>
WARN IF Count > 0 IN SELECT FIELDS 
WHERE 
 FieldCa == 0 AND  // Ca=0 -> No Afferent Coupling -> The field is not used in the context of this application.
 !IsPublic AND     // Although not recommended, public fields might be used by client applications of your assemblies.
 !IsLiteral AND    // The IL code never explicitely uses literal fields.
 !IsEnumValue AND  // The IL code never explicitely uses enumeration value.
 !NameIs "value__" // Field named 'value__' are relative to enumerations and the IL code never explicitely uses them."
Patrick Smacchia - NDepend dev