The use of readonly

Marc W

Member
Joined
Oct 8, 2014
Messages
8
Programming Experience
Beginner
What is the use of making the class member timeouts readonly in the code below, what is the effect? I think the content of the timeouts list can still be changed, the only thing that is being prohibited is assigning a new Dictionary object to it. Is that right? And is this good coding, since no programmer would think of assigning a new value to the initialized list anyway, after it is constructed. Why is the keyword readonly put here? I think it prohibits something nobody will do anyway, but I could be wrong.
private class Processor
{
    readonly Dictionary timeouts = new Dictionary();
 
Last edited by a moderator:

jmcilhinney

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
3,274
Location
Sydney, Australia
Programming Experience
10+
You're quite correct about what it does and why. What you're not right about is that no programmer would ever replace the Dictionary with a new one. They certainly shouldn't but that certainly doesn't guarantee that they won't. By declaring the field readonly, it IS guaranteed that they won't.

Don't simply assume that people will always do the right thing when there's an easy way to ensure that they do. You may not have been around long enough to experience this yet but it's quite possible to write code yourself, leave for some months, come back to it and have absolutely no idea what you were thinking when you wrote it. If you see a field declared readonly then you know straight away that you didn't intend for that field to be set again whereas if you don't use readonly then you'd have to work that out by context, which is unreliable. If you can be explicit, be explicit.

This question falls into the same category as why to scope everything as narrowly as possible. Sure, you could declare all your variables at the class level and still only use them locally but why would you do that when you lose nothing by declaring them locally and gain clarity?
 

jmcilhinney

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
3,274
Location
Sydney, Australia
Programming Experience
10+
Thank you. Can you tell me how to Fix the code formatting myself, I cannot find it.

You can simply edit your first post to see what it now looks like or, if you can't do that because you haven't got enough posts, simply click the Reply With Quote button.
 
Top Bottom