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.
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")]
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.
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 am working with Visual Studio 2013 and Resharper 8. I would like to be able to check my c# objects to understand if there are properties on them that are not used/referenced ie. find useages in batch.
I want to remove properties that are not being used and remove them.
Is there any easy way or automated way of achieving this?
You can do this using the "Find Usages" option:
Open up the class
Place the cursor on the property you want to search for
Press Shift + F12 (or right-click and select "Find Usages")
If the a property is not being used in the current solution, it'll tell you so:
I don't know of any way to run this for every class in the entire project / solution.
Is there any easy way or automated way of achieving this?
Solution-Wide Analysis:
Solution-wide code inspections are warnings or suggestions, that can be only detected by analysing the whole solution (unused public members, classes, and parameters, unassigned fields, suspicious type conversions etc.). These issues are highlighted in the opened files in the same way as other issues, and they also appear in the Inspection Results window when you run code inspection in specific scope.
Emphasis mine.
Note that ReSharper can only see explicit usages. If you use reflection in some way to access a member, this won't be considered by ReSharper. You can tell ReSharper about implicit usages with the UsedImplicitlyAttribute,
Not sure about automated, but there is a right-click context command when you click on the property/function/field called "find usages", which will tell you if the code is not used.
I have a class with a list property that seems to lose an element under certain circumstances. I cannot find out when this happens.
So what I'd like to do is set up a Visual Studio breakpoint that will pause the program the moment this value changes. A conditional breakpoint would not work in this scenario, since I have no idea what is removing this breakpoint.
To put it another way, I want my program to stop the moment myList.Count evaluates to a new number.
Any ideas on how to do this?
This is not possible in C# or any of the other .NET languages due to CLR limitations. The Visual Studio native code debugger supports data breakpoints (link) for C++ code which do exactly this but this is not supported for managed code. You could try to break on or intercept Add and Remove method calls on the collection as suggested in the other answer to this question.
What about swapping out List<T> for ObservableCollection<T> and listen for the CollectionChanged event? It implements the IList<T> interface so there should be enough overlap in available methods to result in syntax and semantic compatibility.
This is now possible in Visual Studio 2019.
See release notes here: https://learn.microsoft.com/en-us/visualstudio/releases/2019/release-notes
This article goes into some detail using Preview 2.
https://devblogs.microsoft.com/visualstudio/break-when-value-changes-data-breakpoints-for-net-core-in-visual-studio-2019/
Note that this is for .NET Core only and not the soon-to-be-legacy full fledged Windows only .NET framework.
I'm assuming Visual Studio is IDE.
Set a breakpoint, right click it, select condition, type myList.Count, and choose Has Changed.
Subclass List<t> with your own class, then override Count (or Add/Remove) and add a breakpoint in the method you create.
EDIT: As mentioned in comments, this would require a great deal of effort since the Add and Remove methods aren't virtual; a complete rewrite of the methods would be needed.
Also, subclassing Collection<t> would apparently be a better solution (though I can't discern a reason why since Add/Remove aren't virtual members for Collection<t> either; comments?).
You can set data breakpoints in visual studio but this is going to be difficult to do for managed code, as the garbage collector may move the object around. That said, you may still be able to pull it off. You will have to enable native debugging for your process. Load SOS in the immediate window and use !DumpObject to find the address of the backing store for the Count property. Using this address, create a new data breakpoint with this address and then continue and trigger the issue.
Find all usages for this particular property and add breakpoint to all lines that removes elements from this list.
Or you may create your own IList implementation and set breakpoint to Remove method (you can't subclass List without changing all you clients, because List::Remove isn't virtual).
This is maybe more of a question than an answer, but you can step into Framework code when debugging, provided you set up your Visual studio that way. It could be that you can then put the breakpoint into the actual List implementation.
this may sound too out of the way or complex but can you use timer/background thread to keep testing the count value and do a Debugger.Break() whenever it finds the value different from its previous instance.