The most cumbersome piece of syntax I need to continually write is lazily initializing a container in a dictionary like:
ContainerRecord value;
if(!_dictionary.TryGetValue(key,out value))
{
value = new ContainerRecord();
_dictionary[key] = value;
}
//Container is always initialized here
Which I feel would be a trivial refactor pattern from: (At least for the explicit variable declaration and if statement part)
var value = _dictionary[key];
I know there is some new syntactic sugar in newer versions of C# that eliminate the need for pre-declaring out variables. Unfortunately I don't have access to these features in my environment and won't for the foreseeable future.
There does appear to be a "check for contains key" refactor, which is achieves almost the same result with the downside of doing the lookup twice.
Is this possible through some extension? I figured it is a common enough case that it would have already been solved somewhere.
You can create a Custom Pattern for this.
Add the following four placeholders with the Add Placeholder button:
Enter the following as the Search pattern in the text area on the top:
Enter the following as the Replace pattern in the text area on the bottom:
Optional: Fill out the Description on the top. I used
Replace with TryGetValue
.The finished dialog should look like this:
Save
button.Custom Patterns
, you can set the severity level for your new pattern on the right side using the dropdown. I selected Suggestion.If you set up everything correctly, ReSharper should mark the matching patterns with the suggested fix: