Why is ReSharper suggesting readonly field for 'settings' in my example below?
If I understand correctly, you should use readonly
modifier if you change this field only in constructor, but in my example I also change it in another method in the same class.
What am I missing?
public partial class OptionsForm : Form
{
private Settings settings;
public OptionsForm(Settings s)
{
settings = s;
}
private void SaveData()
{
settings.ProjectName = TextBoxProject.Text;
}
}
When a reference type is declared as readonly, the pointer is immutable, but not the object it points to. This means that:
- a reference type data member can be initialized in order to point to an instance of a class, but once this is done it's not possible to make it point to another instance of a class outside of constructors
- the readonly modifier has no effect on the object the readonly data member points to.
Read a detailed article on this
Mark a C# class data member as readonly when it’s read only
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