Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does resharper suggest readonly fields

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;
    }
}
like image 920
sventevit Avatar asked Oct 14 '09 11:10

sventevit


1 Answers

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

like image 126
rahul Avatar answered Sep 22 '22 12:09

rahul