I want to delete foo() if foo() isn't called from anywhere.
views:
1391answers:
7Resharper does this, and not just with methods. It also does it with using statements, variables etcetera.
HTH, Kent
Gendarme will detect private methods with no upstream callers. It is available cross platform, and the latest version handles "AvoidUncalledPrivateCodeRule".
FxCop will detect public/protected methods with no upstream callers. However, FxCop does not detect all methods without upstream callers, as it is meant to check in the case that your code is part of a Library, so public members are left out. You can use NDepend to do a search for public members with no upstream callers, which I detail here in this other StackOverflow answer.
(edit: added information about Gendarme which actually does what the questioner asked)
Well, if VS doesn't do this natively, a simple method is to right click on the method and select "find all references" . If there is only 1 reference (where it is declared) it most likely isn't used anywhere else.
Bear in mind that Resharper (and probably other similar tools as well) will not highlight unused methods if the methods are marked public
. There is no way a static code analysis tool will be able to check whether the methods of your assembly are used by other assemblies outside your solution. So the first step in weeding out unused methods is to reduce their visibility to private
or internal
.
NDepend can report dead code thanks to CQL queries or rules such as:
// <Name>Potentially unused methods</Name>
WARN IF Count > 0 IN SELECT TOP 10 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 // The IL code never explicitely
AND // calls explicit interface methods
// implementation.
!IsClassConstructor AND // The IL code never explicitely
// calls class constructors.
!IsFinalizer // The IL code never explicitely
// calls finalizers.
or
// <Name>Potentially unused types</Name>
WARN IF Count > 0 IN SELECT TOP 10 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" // Generally, types named Program
// contain a Main() entry-point
// method and this condition avoid
// to consider such type as
// unused code.