Removing unused code in Visual Studio

Matthew Layton picture Matthew Layton · Oct 9, 2012 · Viewed 40.4k times · Source

In relation to this question: "Remove unused references (!= "using")", I would like to know if there is a tool for removing unused classes, structs, delegates, etc from a Visual Studio solution.

Scenario:

I have an unorganised Visual Studio Solution which consists of 1000's of:

  • Native method imports
  • Structures
  • Delegates
  • Enumerations

Rather than trawling through each file clicking "Find All References" and determining if the code is being used somewhere, is there any mechanism by where I can simply remove redundant code files easily?

Example:

//This class contains a method called getRandomValue which returns type RANDOM
public class NativeMethods
{
    [DllImport("random.dll")]
    public static extern RANDOM getRandomValue();
}

//This is the RANDOM object as referenced by getRandomValue();
[StructLayout(LayoutKind.Sequential)]
public struct RANDOM
{
    uint a;
    uint b;
    uint c;
}

//This is redundant since nothing is referencing it.
[StructLayout(LayoutKind.Sequential)]
public struct MESSAGE
{
    IntPtr sender;
    IntPtr recipient;
    char[] mText;
}

Note to self:

My gut feeling is that this is going to be tricky since unlike Java, object names do not have to be identical to the file name, and multiple object declarations can reside within a single file, however in this instance (my scenario) every object is declared within its own file (with an identical name).

Answer

Dmitry Khryukin picture Dmitry Khryukin · Oct 9, 2012

ReSharper is the best choice to clean up your code.

You can use it for free thanks to ReSharper Early Access Program.

enter image description here