Resharper - keep named parameters when doing code cleanup - c#

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).

Related

Resharper convention for "event subscription on fields" to start with uppercase?

This question is based on the original message that you find here:
ReSharper conventions for names of event handlers
I have the same question like the commenter on the second answer: Is it possible to let the Event subscription by default start with an uppercase letter? So if the button is called "btnOK", generate a method called "Btn"?
And before you asked, I'm aware of Jon Skeets answer, but still am curious if this is possible.
Thanks in advance!
For any event added in code/xaml (e.g. added with ReSharper's Create Method) the Naming Style settings of ReSharper will apply (see ReSharper->Options->Code Editing->C#->Naming Style).
As for anything named by the Designer View you have to stick to renaming. You could speed up things a little by using Refactoring Rename (Ctrl+R+R). Once the dialog is open press down array and use the first suggestion (which is also according to the set Naming Style).
You could of course always make a feature request at JetBrains but I think it is quite likely what you want is not possible because otherwise I think they would already have added such a feature. Still asking wont do any harm.

VS CodeLens on Properties

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.

How to prevent resharper from juggling back and forth implicit and explicit variable declaration?

I've recently started using resharper and have been following its advice while writing, including that usually it tells me to use implicit variable declaration. However when then using the code cleanup function it just turns them all back to explicit, promptly warning me that I should change them back again. How can I do something about this? Preferably I would want to keep it implicit.
When ReSharper asks you to change something you can click on the little warning icon it spawns on the left and click Inspection options for "..." and change the severity or the convention so ReSharper will leave you alone on that specific convention error.
If you do want this convention only don't want ReSharper to change it back, see this question: Resharper - How to turn off 'private' access modifier?
The only way to achieve this seems to be to create your own code profile, manually copy over the default settings, configure it to keep implicit/explicit the same, then always use that profile. You cannot edit the existing profiles or copy them, you need to entirely create a new one from scratch.

Change each c# file in solution

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#

How do I find all places that SET a property?

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.

Categories

Resources