Tool to find all unused Code - c#

I need a tool I can run that will show me a list of unused methods, variables, properties, and classes. CSS classes would be an added bonus.
I heard FXCop can do this? or NDepend or something?

Look at ReSharper.

Code Analysis in VSTS will generate warnings about this during the build process. You can set it up to treat Warnings As Errors.

You can use ReSharper to find unused code and Dust-Me Selectors to find unused CSS.

The tool NDepend can help find unused code in a .NET code base. Disclaimer: I am one of the developer of this tool.
NDepend proposes to write Code Rule over LINQ Query (CQLinq). Around 200 default code rules are proposed, 3 of them being dedicated to unused/dead code detection:
Potentially dead Types (hence detect unused class, struct, interface, delegate...)
Potentially dead Methods (hence detect unused method, ctor, property getter/setter...)
Potentially dead Fields
NDepend is integrated in Visual Studio, thus these rules can be checked/browsed/edited right inside the IDE. The tool can also be integrated into your CI process and it can build reports that will show rules violated and culprit code elements.
If you click these 3 links above toward the source code of these rules, you'll see that the ones concerning types and methods are a bit complex. This is because they detect not only unused types and methods, but also types and methods used only by unused dead types and methods (recursive).
This is static analysis, hence the prefix Potentially in the rule names. If a code element is used only through reflection, these rules might consider it as unused which is not the case.
In addition to using these 3 rules, I'd advise measuring code coverage by tests and striving for having full coverage. Often, you'll see that code that cannot be covered by tests, is actually unused/dead code that can be safely discarded. This is especially useful in complex algorithms where it is not clear if a branch of code is reachable or not.

Gendarme has also different rules to find unused code.

Related

Can I use ReSharper to enforce commenting standards?

Been playing a lot recently with ReSharper and one thing I'd love to setup for my team are notifications if a C# class or C# file doesn't have a set code commenting standard. Unfortunately I have not yet been able to find much on the topic.
For example, I'd like to ensure all methods or functions have a comment description above them:
/// <summary>
/// Description of MyMethod here.
/// </summary>
public void MyMethod();
I would like to also see that a basic check for whether (Number of lines of code) / (Number of lines of comments) is around some magic happy-medium, and create a notification or warning if not.
One simple option to start with (which doesn't even need R#) is to turn on the generation of an XML documentation file, and then treat warnings as errors. That will ensure that every public member has documentation.
It won't ensure that the comments are good, of course... but it will ensure they exist.
EDIT: R# does have a setting for this - under Code Inspection, Inspection Severity, C#, Compiler Warnings, look for CS1591: Missing XML comment for publicly visible type or member (and related warnings near it). Change the severity of that to Error and it might help you - but it's hard to say as you're in an unusual environment.
Not to compete with Jon but GhostDoc does what you're describing.
Also, check out StyleCop which has a Resharper plugin, which means missing comments (for methods, properties, etc) will be shown as Resharper warnings/errors. May, or may not, be of interest for you, but at least it's an option.
There are two options. Both - using extensions for ReSharper - not for Visual Studio (if you didn't know, ReSharper has its own Extension Manager). These extensions are (use the second one!):
AgentSmith (for R#9). Now, my ReSharper's Extension Manager says, that this extension is for ReSharper of the version 9.0 (which I have installed) but, in fact, this extension works with errors (disabling of highlights works not properly).
XML Doc Inspections for ReSharper 9. Seems, works without any problems (I have it just installed). That is what you really need to highlight classes, methods, properties and so on (even private fields) that have no XML comments!
Stylecop has many rules for comments, you may also want to look at Stylecop+ as this has some extra rules for Method/Property lengths.

Removing unused code in Visual Studio [duplicate]

This question already has answers here:
Removing all unused references from a project in Visual Studio projects
(16 answers)
Closed 2 years ago.
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).
ReSharper is the best choice to clean up your code.
You can use it for free thanks to ReSharper Early Access Program.
There are several tools that you can use to do this:
FxCop (free)
NDepend (paid)
Resharper (paid)
FxCop will only find unused internal and private code. Of course if you make sure you only publicly expose code that needs to be accessible outside your assembly, then that should be good enbough.
As pointed #Ergwun the tool NDepend can help to find unused methods, fields and types.
To elaborate a bit, NDepend proposes to write Code Rule over LINQ Query (CQLinq). Around 200 default code rules are proposed, 3 of them being dedicated to unused/dead code detection
Basically such a rule to detect unused method for example looks like:
// <Name>Dead Methods</Name>
warnif count > 0
from m in Application.Methods where !m.MethodsCallingMe.Any()
select m
But this rule is naive and will return trivial false positives. There are many situations where a method is never called yet it is not unused (entry point, class constructor, finaliser...) this is why the 3 default rules are more elaborated:
Potentially dead Types (hence detect unused class, struct, interface, delegate...)
Potentially dead Methods
Potentially dead Fields
NDepend integrates in Visual Studio 2022, 2019, 2017,2015, 2013, 2012, 2010, thus these rules can be checked/browsed/edited right inside the IDE. The tool can also be integrated into your CI process and it can build reports that will show rules violated and culprit code elements. NDepend has also a VS Team Services extension.
If you click these 3 links above toward the source code of these rules, you'll see that the ones concerning types and methods are a bit complex. This is because they detect not only unused types and methods, but also types and methods used only by unused dead types and methods (recursive).
This is static analysis, hence the prefix Potentially in the rule names. If a code element is used only through reflection, these rules might consider it as unused which is not the case.
In addition to using these 3 rules, I'd advise measuring code coverage by tests and striving for having full coverage. Often, you'll see that code that cannot be covered by tests, is actually unused/dead code that can be safely discarded. This is especially useful in complex algorithms where it is not clear if a branch of code is reachable or not.
Disclaimer: I work for NDepend.

Which are the differences between StyleCop and Code Analysis when talking about the rules of each?

Could you please tell me which are the differences between rules of StyleCop and Code Analysis ? Should it be used together or not ?
Thanks.
Style cop essentially parses the file looking for formatting issues and other things that you could think of as "cosmetic". Code analysis actually builds your code and inspects the compiled runtime IL for characteristics about how it behaves when it runs and flag potential runtime problems.
So, they are complimentary, and you are perfectly fine to use them together.
Short answer:
stylecop: takes your source code as input and checks for potential code style issues. For instance: using directives are not alphabetically ordered...etc.
fxcop (now code analysis): takes a compiled assembly as input and checks for potential issues related to the executable/dll itself when it'll be executed. For instance: in your class you have a member of type IDisposable that is not disposed properly.
However, there are some rules that are common to both tools, for instance rules related to naming convention for public exposed types.
Anyway, using both is a good idea.
FxCop checks what is written. It works over the compiled assembly.
StyleCop checks how it is written. It works over the parsed source file, even without trying to compile it.
This leads to all the differences. For example, FxCop cannot check indentations, cause they are absent in a compiled assembly. And StyleCop cannot perform code-flow checks cause it doesn't know how your code is really being executed.

Where can I modify detailed C# compiler optimization settings in Visual Studio?

In Visual Studio C/C++ projects, it's easy to modify compiler's optimization settings in "Property Pages | C/C++ | Optimization". For example, we may give different optimization levels such as /O2 and /O3, as well as advanced optimizations like "Omit Frame Pointers".
However, I can't simply find corresponding UIs in C# project of Visual Studio. All I can find is just turning off optimizations: the "Optimize code" check box is all I've got.
Can C# users control detailed compiler's optimizations like C/C++? Do I have to give compiler options in command line?
Much of the optimisation of C# code goes on at the JIT compiler level, rather than the C# compiler. Basically there are no such detailed settings as the ones available in C or C++.
There are a few performance-related elements of the runtime that can be tweaked, such as GC strategies, but not a great deal.
When I'm building benchmark tests etc from the command line I tend to just use something like this:
csc /o+ /debug- Test.cs
(I believe I have seen the presence of a matching pdb file make a difference to performance, possibly in terms of the cost of exceptions being thrown, hence the debug- switch... but I could be wrong.)
EDIT: If you want to see the difference each bit of optimization makes, there's one approach which could prove interesting:
Compile the same code with and without optimization
Use ildasm or Reflector in IL mode to see what the differences are
Apply the same changes one at a time manually (using ilasm) and measure how much each one has
AFAIK C# compiler has no such detailed optimization properties. Probably optimization is either enabled or disabled.
http://msdn.microsoft.com/en-us/library/6s2x2bzy.aspx
I found just two:
/filealign Specifies the size of sections in the output file.
/optimize Enables/disables optimizations.
A bit OT, but someone looking at this question might find this useful:
Adding this to method signature:
[MethodImpl(MethodImplOptions.NoOptimization)]
turns off compiler optimizations for that method.
See here for details:
https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.methodimploptions%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

Problem with Reflector and Automatic Properties

I've just disassembled a project to debug it using Reflector, but it seems to balk at decoding the 'compile results' of automatic properties, e.g. the next line gives me a syntax error. I've tried fixing these manually, but every time I fix one, more appear.
private string <GLDescription>k__BackingField;
Is there anything I can do about this?
Ha! Stupid me: all I had to do was set the disassembler optimization in Reflector's options to .NET 3.5. Mine was on 2.0.
The compiler generates fields with "unspeakable names" - i.e. ones which are illegal in C# itself, but are valid IL.
There's no exactly accurate translation of the IL into "normal" C# (without automatic properties). You can replace < and > with _ which will give legal code, but then of course it won't be exactly the same code any more. If you're only after the ability to debug, however, that won't be a problem.
If you decompile iterators (i.e. methods using yield statements) you'll find more of the same, including the use of fault blocks, which are like finally blocks but they only run when an exception has occurred (but without catching the exception). Various other constructs generate unspeakable names too, including anonymous methods, lambda expressions and anonymous types.
On a broader note, do you have permission to decompile this code? If the author doesn't mind you doing so, they're likely to be willing to give you the source code to start with which would make your life easier. If they don't want you debugging their source code to start with, you should consider the ethical (and potentially legal) ramifications of decompiling the code. This may vary by location: consult a real lawyer for more definitive guidance.
EDIT: Having seen your own answer, that makes a lot of sense. I'll leave this here for background material.

Categories