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?
7
If you think it’s confusing, as you’ve said, then don’t do it. If other members of your team that are likely going to need to work with this code don’t have the difference between references and objects sufficiently ingrained in their brains then don’t do it to avoid confusing them. If you all understand the concepts so effectively that this isn’t confusing at all, and you think it might benefit you to convey that the reference to the list isn’t changed, then mark it as read only.
Keep in mind that your team doesn’t always need to do the same thing as everyone else on the planet. Do what works best for the people who will actually need to touch this code (with some basic considerations for people who will need to touch the code that aren’t yet on the team.)
0
I say yes, add the readonly
. For two reasons:
-
if you (or a teammate in the future) try to reassign to that variable in a later method, it will give you a compile-time error. R# will note the error even earlier. So, it’s best thought of as an indicator and enforcer of intent. Even if you intend to reassign it later, it forces you to think about the design a little more and will not hurt much to remove it.
-
the compiler and/or JITter can use the single-assignment knowledge conveyed to potentially provide optimizations. Not guaranteed, but I do it for the first reason – this is a possible bonus.
4
You are getting the suggestion because you aren’t changing the list itself, just the contents. If you reassigned the list entirely somewhere it would not be readonly, but because you are simply updating the contents the list itself doesn’t change.
This is similar to how you can have a readonly object, but still change values on that object. The member variable does not change, but the object itself is still mutable.
3