How to prevent collection modifications in .NET


Hello. Today I am going to write short article about one particularly useful method AsReadOnly that can be found on List<T> and Array classes.

I find this method useful because it allows protecting collection from external modification. Let’s look at the example below:

public class PersonalManager { public IEnumerable<string> EmployeeNames { get { var names = new List<string> { "John", "Patrick", "Edward" }; return names; } } }

Here we have PersonalManager class, which can provide names of employees he is responsible for. As you can see, EmployeeNames property returns implementation of IEnumerable<string> that explicitly tells its clients that this property for enumerating purposes only. But as you know, there will always be some kind of “smart” developer who will explicitly cast returned value and perform modifications:

private static void Main(string[] args) { List<string> names = new PersonalManager().EmployeeNames as List<string>; names[0] = "New"; }

This code works just fine and it effectively breaks encapsulation of PersonalManager class.

Fortunately, PersonalManager class can be changed in the following way to prevent this:

public class PersonalManager { public IEnumerable<string> EmployeeNames { get { var names = new List<string> {"John", "Patrick", "Edward"}; return names.AsReadOnly(); } } }

After this change, clients of PersonalManager won’t be able to modify EmployeeNames collection and they will have up-to-date collection in case some employee is added.

Advertisements