Friday, 9 August 2013

Should I make a variable readonly when I modify it, but I don't actually set it outside of the constructor?

Should I make a variable readonly when I modify it, but I don't actually
set it outside of the constructor?

Background:
I was writing some code. It looked something like this:
class X
{
private List<int> _myList = new List<int>();
public void MyMethod(int x)
{
_myList.Add(x);
}
}
R# suggested that I make _myList readonly. I wasn't so sure, as though I
technically could make it readonly, I think it would be slightly confusing
to do so, as I'm still modifying the list, just not reassigning it. So
while I could make it readonly, I'm not sure if I should.
Question:
Should I make variables like this readonly? Why? If not, why does R#
suggest this?

No comments:

Post a Comment