216

In visual studio 2013 the number of references of a special Code(method, property, field,...) is shown by Code Lens. I want to get unused (zero reference) Code in visual studio. Is there any way to get them?

I mean below reference:
enter image description here

starball
  • 20,030
  • 7
  • 43
  • 238
Nima Rostami
  • 2,652
  • 3
  • 15
  • 23
  • could you please explain more about it? – Nima Rostami Jun 22 '15 at 07:46
  • 29
    I think he wants a list of all methods which are not referenced, rather than to bring the number of references of that particular method to zero. – Jurgen Camilleri Jun 22 '15 at 07:46
  • You want to get all unused methods? – Yuval Itzchakov Jun 22 '15 at 07:46
  • 1
    yes I want to find all unused codes contain Methods, Properties, etc. – Nima Rostami Jun 22 '15 at 07:49
  • 1
    Remember that you can't be sure that a `public` is unused without searching the entire code base. However, for unused internals and privates, Code Analysis will warn you if you have the appropriate warning enabled. – Matthew Watson Jun 22 '15 at 07:58
  • 11
    I really isn't that misleading... the screenshot tells you what reference he's referring to. His post if you read it tells you he wants to find all that would display as 0 references. Not that difficult. – Ryan Sep 15 '21 at 11:16
  • 1
    Note that if you see "0 references" it _does not_ necessarily mean the code is not used. For example, LINQ methods in certain contexts may rely on the presence of an overridden `Equals` method. Removing a 0 reference `Equals` won't lead to a build error, but any methods relying on it will silently produce incorrect results at runtime. – Tawab Wakil Sep 14 '22 at 21:48
  • @CaptainKenpachi questionable implication that there's anything to calm down. ;) I've deleted my comment from 5 years ago. – Sinjai Oct 31 '22 at 18:27

6 Answers6

226

Probably the best and easiest way to achieve what you are after is to use the build-in code analysis tool with Visual Studio to find and take you directly to dead code and unused members.

To this effect, I created a new code analysis ruleset file (Via File->New->File, making sure General in the left pane was selected and scrolling down to find Code Analysis Rule Set, giving it a filename, then searching for and selecting the below rules). See below for the contents of the ruleset file that you can copy, and paste into a new file with the extension .ruleset to use.

Given a ruleset file, one can right click on a project file in the Solution Explorer panel, and select Properties. In the project properties windows, click on the Code Analysis tab in the left panel, and then click Open to browse to the .ruleset file's location. If you go to the properties of a solution file (as opposed to a project file), you can set the code analysis file for each project in the solution in one place (under Code Analysis Settings, and using the drop-down there to select the ruleset file. NOTE: You must have previously have browsed to the ruleset file for it to show up in the drop-down in this properties window, however).

Then you simply run the code analysis on the projects/solution (Via Analyze->Run Code Analysis On Solution -OR- Alt+F11) and it will come back as warnings, any unreferenced methods or unused members it finds. It will even find methods that are referenced by a method, whom itself has no references elsewhere.

Be careful however, as one of the ways code analysis for dead code can steer you wrong, is if the reference is 'hidden' by only ever calling the method via delegates, and of course, reflection.

The rules to detect dead code, specifically, are:

  • 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).
  • Dead code in bitwise-OR limited switch (C6259)

Below is the contents of the .ruleset file that can be had by following the steps above, for your conveinence. You can simply copy the below XML, paste it into notepad++, save somewhere with the extension .ruleset, browse for and use as explained above:

<?xml version="1.0" encoding="utf-8"?>
<RuleSet Name="Dead Code Rules" Description=" " ToolsVersion="12.0">
  <Rules AnalyzerId="Microsoft.Analyzers.ManagedCodeAnalysis" RuleNamespace="Microsoft.Rules.Managed">
    <Rule Id="CA1801" Action="Warning" />
    <Rule Id="CA1804" Action="Warning" />
    <Rule Id="CA1811" Action="Warning" />
    <Rule Id="CA1812" Action="Warning" />
    <Rule Id="CA1823" Action="Warning" />
  </Rules>
  <Rules AnalyzerId="Microsoft.Analyzers.NativeCodeAnalysis" RuleNamespace="Microsoft.Rules.Native">
    <Rule Id="C6259" Action="Warning" />
  </Rules>
</RuleSet>
ToolmakerSteve
  • 18,547
  • 14
  • 94
  • 196
Adam White
  • 3,180
  • 1
  • 21
  • 18
  • 43
    I don't think this completely answers the question. The main difference is CodeLens will tell you that a PUBLIC method has zero references in a entire solution. This is the key. FxCop, R#, and your method for great for anything not public. – Scott Wylie Jun 23 '16 at 22:55
  • 1
    @ScottWylie - I disagree. I Just tried the above solution and it did not flag un-referenced public methods. CodeLens was exceptional at flagging dead code, unreferenced local stuff and unused variables. I think this gets most people exactly what they want w/o using a 3rd party tool. – mike Nov 30 '17 at 06:05
  • 14
    @mike Consider this: If you want to find dead code with a mass operation you tend to not care about private/protected members, because these are local problems. For example, I am migrating a 500k+ LoC project with 100+ projects and 10+ solutions to a repository pattern architecture. After migrating a component, I need to know which old interfaces I can delete. Some IDEs like Eclipse have tools for exactly that. Greyed-out local methods are simply not my concern, I'd like a list of PUBLIC classes/interfaces where code lens would tell me "0". – Oliver Schimmer Apr 16 '18 at 20:57
30

If your code base is small enough, and doing it manually is an option for you, then I would go through each file, do the Ctrl-M-O command to collapse everything, then scroll around looking for the reference 0.

MyDaftQuestions
  • 4,487
  • 17
  • 63
  • 120
user1730026
  • 389
  • 3
  • 3
11

In Visual Studio | Error List tab | Messages tab: Message IDE0051 Private member 'xxxxxxxx' is unused.

7

https://scottlilly.com/c-code-quality-improvement/remove-unused-classes-properties-and-functions/

"Unfortunately, [in Visual Studio Analysis] you can only detect unused private members. This is because the code analyzer assumes public members might be used by other programs. This could be true if you’re publishing them as an API through a web service or releasing your code as a library. ... ReSharper has similar code analysis functions – with the advantage of checking for unused public members."

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
V Frenkel
  • 91
  • 1
  • 1
  • 1
    Yes, but is there no option that makes the heroic (i.e., on your head be it) assumption that there are no such public members used by other programs? – Keith Howard Jul 18 '22 at 11:09
6

Here's a manual way to accomplish this that I've used for finding unused Classes that are marked public.

  1. Search and Replace all "public class" with "private class" for one project in your solution. May also need to replace "public static class" and/or "public abstract class".
  2. Build to find all the errors
  3. For each error in the build, use your source control to restore the file for the referenced class.
  4. Repeat for every error until the build succeeds.
  5. Any remaining files that haven't been restored are likely candidates for removal.
  6. (optional) Rename the classes in the above files and do one more build to find errors.
  7. Do one last Search for the name of the class you want to remove to confirm there aren't any instances of it being used in reflection or magic strings.
  8. Remove the identified unused class files.
  9. Repeat for each solution project you want to clean.

Note: If you don't follow the one class per file rule, this will require a lot more work. Also, any API service endpoints you will need to verify that it is not being used by any external projects.

Ulfius
  • 619
  • 7
  • 14
  • 47
    This is not at all practical. – Don Rolling Sep 24 '19 at 15:33
  • 6
    It works for me in a large project and is one solution. Cases may vary where it's more difficult, but I wanted to provide this as a possibility. – Ulfius Sep 25 '19 at 16:47
  • 2
    I never said it was practical. It's just a method to find unused public classes. Not everything in programming is practical. – Ulfius Jan 21 '21 at 22:22
  • 12
    I am voting up, because this is at least a method that actually does what I want, namely find unused public classes. Yes, this is impractical for huge solutions, and even in small solutions doesn't scale for methods and fields. But it's something that I can do without the need to buy Resharper for $300/year. Saying it's not practical is like saying "poor man's debugger" aka `Debug.WriteLine` is not a solution to find a problem just because it's not practical. But if your free debugger doesn't work and otherwise you need hundreds of $, it IS an option I might be interested to hear about. – LWChris Mar 18 '21 at 14:55
  • Not everything in life is practical , thx Ulfius :P – HelloWorld Jun 17 '21 at 14:51
  • it's a dangerous method – D. Pesc. May 28 '23 at 15:21
2

The best solution I can find is Resharper, you can then run the tool's analysis and look for "Type member is never used". I know this is not ideal but it's the best solution I can find.

Inverted Llama
  • 1,522
  • 3
  • 14
  • 25