I have a class that has about 1200 constant fields. I know that some of them (maybe 10%) are deprecated/legacy fields that have 0 references in the solution. Instead of going one by one and find all references, I thought that CodeLens would show me the number of references on top of each field. Unfortunately, it turned out that CodeLens doesn't provide info for fields, only methods, classes, and properties. Is there a way to find out the "useless" fields in the class? If not, is there a way to enable CodeLens (or a similiar extension) for fields?
As Arturo commented, code lens works fine for properties, it doesn't work for public fields.
What I would do in your case is try commenting out say 10 or 15 at a time, and then trying to compile. The error messages will show you which are needed, and you can uncomment those. This will leave the unneeded ones commented out. They can then be deleted.
The other way to do it is to copy the lines of code into a text editor and use a macro to turn each field into a property. Then paste these lines back in, and code lens will work.
Both ways will work, depends which you prefer. I'd prefer the latter, but it's largely personal.
Visual Studio has a great code analysis tool built into the IDE. Here is a great article to help you find and eliminate "dead code" (unused properties, fields, etc) using code analysis.
Related
What do these three gray dots mean? I recently updated to Visual Studio 2017, and I haven't ever seen them in other versions of VS.
They indicate suggestion from Visual Studio to refactor your code to be simpler, more readable and efficient.
See Quick Actions and Refactorings section of the Visual Studio 2017 (version 15.0) Release Notes.
Just to make doubly clear for newish programmers, these are not in any sense error messages. They are merely suggestions for more "readable and efficient" code as #Oleksander states.
Some may not be the best advice for your application, unlike warning or error messages, which almost 100% are in my case at least.
I had suggestion in a Unity game engine C# application to make a variable "readonly". I'm not sure in my case it makes practical difference whether this is readonly or not, as in this case I think fairly obvious in the context: a private variable which is serialized and can be set in game's editor program, nobody likely to create new method in this game scene manager class to alter/assign this variable. Likewise it gave a suggestion to create property for a class private field, which I think extra code overkill.
At the least these are low priority messages to action.
Suppressing 3 Dot Symbols in Visual Studio
If you right click and read through one of these suggestions, you can find there is option to suppress these messages in global project file, with various optional parameters. So eg in my case, now I don't want any readonly message suggestions for whole project (welcome correct me anyone more experienced if this is bad idea!), so in the root of project, same level as .sln solution file, .csproj files, .git file in my case for C# project, it saves file called "GlobalSuppressions.cs". Root location and this exact file name is presumably crucial.
I guess if you want stop future coders / future you from fretting or spending time on these 3 dot messages when you think waste of time, could be useful.
In my case, to get rid of all "readonly" keyword suggestions in this project, code is (comments are VS auto comments):
// This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier")]
We've adopted a convention that when calling a C# function with a "non-obvious" parameter, we use a named parameter even when it's not necessary.
E.g.
obj.Process(save: true)
rather than
obj.Process(true)
While it's unnecessary, it makes it a lot easier when glancing through the code to see what's going on, particularly with booleans or magic numbers.
However, resharper's code cleanup has a habit of removing these. I haven't been able to find a way to tell it to keep named parameters - is there one?
Although you can achieve it by doing what #EricWalker said, I want to propose another option.
You can start up the ReSharper options, look for Inspection Severity then go to Redundant explicit argument name specification and change this to do not show. This way you won't lose all the other good cleanups (like removing full name qualifiers) that remove redundant code offers.
In ReSharper 2018.1
There are two relevant steps. You will likely want to do both, but it depends on how you want ReSharper configured.
First, in Resharper -> Options -> Code Inspection -> Inspection Severity, disable the "Use preferred argument style for literal values" code style. (For bools, "[..] for literal values" is the relevant setting, though I chose to disable all of them.)
This setting is also linked to the ReSharper -> Options -> Code Editing -> Code Style -> Arguments settings, so these should now be automatically changed to "Do not show" instead of "Hint":
Second, the default ReSharper Code Cleanup profile cannot be used due to the "Apply arguments style (named vs. positional)" - this option must be disabled in your code cleanup profile.
To show argument names in your method calls, goto:
Resharper ⇨ Options ⇨ Code Editing ⇨ C# ⇨ Syntax Style ⇨ Arguments
Then set all dropdown values to "Named Argument."
Also, check "Skip single arguments" to show named parameters for the method only when there is more than one parameter.
The above approach was verified on Resharper version 2020.2.4
The setting you're looking for is under Code Cleanup\C#\Remove code redundancies
I know that's probably not the answer you were hoping for, but you can stop it removing your parameter names by unchecking that setting (along with leaving behind every other redundancy.)
You might be able to setup different profiles in Code Cleanup to work around the issue, but you'd have better luck asking JetBrains folks for solutions.
HTH,
Eric
UPDATE:
It seems that this solution no longer works starting with v2017.1.3 (2017-08-28)
I'm currently using ReSharper v2017.1 (2017-06-01) and it seems JetBrains hasn't solved this problem yet.
As #Colin Harkness noticed, currently the last resort for keeping "named parameters" is to set the option "Named expressions (variables, properties, methods, etc)" to "Named argument".
This is certainly not the best way out.
UPDATE:
I a little trick found at JetBrains' forum.
You can cancel considering named parameters as a redundancy by adding this line of code at the top of file.
// ReSharper disable ArgumentsStyleNamedExpression
You have to do some minor configuration within ReSharper settings. In order to keep automatic addition of the // ReSharper disable ArgumentsStyleNamedExpression simple, I have added this instruction to File Header Text as is shown in fig. 2.
Fig.2 - Add ArgumentsStyleNamedExpression Rule
After that, you have to check Update File Header option in Code Cleanup Configuration as is shown in fig. 3
Fig.3 - Check "Update File Header" option
In this case, when a Code Cleanup starts, it first adds ArgumentsStyleNamedExpression rule, and applies code style to file.
After adding this rule, you can go to Tools | Options | Environment | Fonts and Colors | ReSharper Parameter Identifier and change the highlighting color for this case in order to visually distinguish arguments and parameters names as is shown in fig 4.
Fig.4 - Parameter name highlighting
Unfortunately, this way of keeping arguments' names doesn't always work (ReSharper can selectively keep/remove names of arguments).
I added two custom classes to my project, namely "AutoSizeGrid" and "AutoSizeGridEditable"
Both derive from DataGridView, but that's probably neither here nor there.
But where they are is seemingly somewhat of a conundrum.
My project builds and runs fine; however, when inspecting it with Resharper, it gives me a "Constraints Violation" for both of these, saying: "Namespace does not correspond to file location, should be: ''
Do I need to change them like so, from, e.g.:
class AutoSizeGrid : DataGridView
...to:
class <Name of my Solution>.AutoSizeGrid : DataGridView
?
I'd rather not, as I don't know if this would force me to delete the prior DGV-derived components from my forms and replace them with the recompiled versions; that would be a pain in the donkey.
As ElVieejo says, it is not necessary to change it if the code compiles. ReSharper (and other code quality tools) recommend you keep namespaces in sync with file paths because that is the Microsoft convention. Namespaces are extremely helpful for keeping code organized, especially as projects/applications get larger, so it's good to have some clear rules and follow them, but they are for readability and separation of concerns, not syntactical correctness.
Is there a tool or set of tools to go through a c# solution and automatically perform certain changes such as enforcing naming schemes and change for/foreach to linq if possible.
I have used Resharper to do some basic solution wide changes, but I would really like it to do more like global renaming.
Specifically, I would like a tool to rename method parameters to proper c# naming schemes. For instance, MethodA(string Field) should become MethodA(string field) and so on.
Resharper has some pretty cool features, including "Cleanup Code", which can be run on multiple files at once.
It will automatically refactor your files based on the settings you've supplied it.
They have a demo version, so you can test to see if it helps with your problem.
http://www.jetbrains.com/resharper/
Resharper`s "Clean Up Code" tool can be run from context menu of any item in Solution Explorer. There are a few built in clean up configurations. You can configure your own. For example, you can set up order of fields\properties\methods\nested types in you class and reordering their before commit by executing clean up tool. It also can wrap its into region and so on.
Also you can force Resharper to use any of refactorings when cleaning up.(Optimize imports, remove unused methods or properties or use linq instead of loops, etc)
You can start looking from there
UPD You can use stylecop plugin to make your code correspond with the style conventions you want. It is open source and compatible with R#
It is easy to find all code that uses a property, however how do I find the code that just sets it?
(When I do a “find all reference” on the “set”, it just does a “find all reference” on the property itself, including code that just reads it.)
You can use Resharper.
Alternately, set the setter to private (Or comment out the setter completely) and recompile. You will get errors where you're trying to set the property.
For what it's worth, this will be natively possible with VS2019.
Specifically the 'Find All References' window has a new 'Kind' column which can be filtered for 'Write' references:
The specific Github PR that added this feature is scheduled to be included in Visual Studio 2019 Preview 2 (16.0.P2) https://github.com/dotnet/roslyn/issues/22545
The full release of VS2019 is roadmapped for Q1 of 2019.
Try commenting the set part of property and build it gives error at all the places where it is used.
You could run a text search on propertyName = - you can try using regex search to allow for 0 to n spaces between the name and =.
AFAIK, this can't be done using the standard features of Visual Studio - it doesn't do anything special for properties to check whether they are being used on the left or right side when searching, and, to be sure, there's no option to tell it to do so.
To give an option without having to run extra regexes or install other software, you could just browse through the results window to let your eyes scan for left-side occurrences - maybe not the most productive but I'm not sure I see a great advantage over other suggestions.
Lastly, #Kamyar's suggestion to make the properties no longer accessible does seem worth a look, but this depends on how long it takes your project to compile, it could take even longer to find'em all - I'm not sure why you'd need Resharper to do this though.
Here's a fairly robust solution that'll work also for non-Properties using Visual Studio without 3rd party tools. Be sure to select the "Match Case" and "Use Regular Expressions" options in Find.
1. For all except Post-/Pre-fix Increment and Shift Assignments:
(^|[^\w.])MyVariable\s*([\+\-\*/%&|\^]|)=[\w\s]
2. For Post-/Pre-fix Increment and Shift Assignments:
((^|[^\w.])MyVariable\s*(\+\+|--)|(\+\+|--)\s*MyVariable[^\w.]|(^|[^\w.])MyVariable\s*(<<|>>)=)
3. For Out / Ref Parameters (N/A for Properties):
(^|[^\w.])(out|ref)\s+MyVariable[^\w.]
CAVEATS:
C#.NET only.
Visual Studio 2012+ only.
Does not work if "=" is followed by an EOL.
Does not work if "MyVariable" is followed by an EOL.
Depending on starting point and scope of the Find and scope of the Variable / Property, may find more / less references than necessary. When in doubt, error on side of "more", so you won't miss anything.
Does not work for "."-prefixed Variables / Properties.
6.1. Unless you include it as part of the "MyVariable" (i.e. "MyStructVariable.MyStructField" or "MyObjectVariable.MyObjectField") but you risk finding too few references since there may be other Struct or Object Variables used to make Assignments to the same Struct or Object Field or Property.