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:
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!
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...)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With