Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell ReSharper to stop creating readonly fields?

This question is similar, but my question seems to get asked in an unanswered comment.

I create a C# class. I use alt-insert to add a constructor. I add an argument to the constructor, and then I use alt-enter to create and initialize a field from that argument, like so:

alt text

The problem is that my field gets created as a readonly field, and in many cases I do not want to create a readonly field.

readonly int my_int;

How can I tell ReSharper not to add make my field readonly? I've tried to do a pretty thorough search in the ReSharper options, but apparently I'm missing something!

like image 855
Chris Farmer Avatar asked Aug 25 '10 14:08

Chris Farmer


3 Answers

I too cannot find any option to change the creation default; however, if you allow R# to create this field as it likes (ie readonly), and later type this:

public void Bar(int baz)
{
    my_int = baz;
}

then the assignment to my_int will get a red squiggly underline, since it is illegal, and the offered quick fix (Alt+Enter) at that location will be Make field 'my_int' non-readonly.

So in the spirit of 'code first', you might want to just let R# do its thing, and also use it to change it as and when you actually need it changed (which might of course turn out to be never...)

like image 98
AakashM Avatar answered Nov 18 '22 17:11

AakashM


The field creation is hardcoded to be readonly on creation. The idea is that you're creating a field, so it doesn't have any usages to default to the most restrictive, if you try to write to it elsewhere, you can alt+enter at that point and remove the readonly status. If the field already exists, ReSharper will try and initialise the existing field from the parameter.

If you want to, you can write a plugin to generate the field as non-readonly. You should look at the IntroduceFieldFix class in dotPeek. It's got several constructors, which binds the quick fix to the warning squigglies, and it will introduce a field using the default pattern for the current language (which is hardcoded to "private readonly $0 $1;")

You can create a class that also derives from InitializeFieldFix, and includes a constructor that takes UnusedParameterWarningBase as a parameter. You can then follow the same implementation as IntroduceFieldFix, but provide a different pattern for the field creation, checking for the current language first.

like image 44
citizenmatt Avatar answered Nov 18 '22 18:11

citizenmatt


Another option may be to use 'Introduce Field' refactoring instead. The best way to call it is to use 'Refactor This' (Ctrl+Shift+R) on a parameter declaration and choose 'Introduce Field' from the reduced number of refactoring options. By default it will generate writable field but there is also an option to change modifiers.

like image 2
Shkredov S. Avatar answered Nov 18 '22 16:11

Shkredov S.