Home of the AlmostImplementedException

Work with ReadOnlyCollection and AsReadOnly to prevent changes on lists

In Java the final-keyword on a parameter indicates that it is not changeable and in C/C++ you could use const. But in C#, there is no way (thanks Microsoft, well done ;-))

In Java and especially with the CleanCode-Paradigma the final keyword is used wherever possible to indicate that you use this variable only as readonly and to get you thinking about what you do, before you try to change something. CleanCode is not only for easier reading, its also a way to minimize soures of errors.

In many cases it is very important to prohibit changes or work with copies of objects.
Think about a single list you use over and over again in your application. Maybe it is even in a Cache. But what will happen if one of your fellow colleagues is sorting the List, or deletes a value? He may not even know that he changes a list others use.
Another example is a List where you want to restrict/control all changes and read-access is favoured.

Luckily, there is an easy way to get the behaviour we want and avoid complications (at least for lists). The method AsReadOnly().
This method returns a ReadOnlyCollection which acts like a read-only wrapper around List and is really fast (O(1)), because it doesn’t copy any elements.
The only problem is, you use another datatype to get the behaviour you want. Thats not a very clean way to code, but we have no other choice here. As mentioned before, in Java you would use final everywhere to produce CleanCode.
Don’t try this in C#!
Use AsReadOnly() on a list you know others use, or build a caching infrastructure with buildin-readonly-behaviour.

But enough about this, here is the example:

As you can see, you need to change the parameter-type to ReadOnlyCollection in order to get the code work. But this also means you can’t simply pass a List as parameter anymore. If you want to allow both, just change the Parameter to IList and you can either pass a List or a ReadOnlyCollection. This way it is possible to call Add but it will lead to an error.
To check if a IList is readonly in advance just use the IsReadOnly flag.

Share :


Leave a Reply