IReadOnlyCollections Hidden Gems Of C#

IMO, IReadOnlyCollections(IReadOnlyList, IReadOnlyDictionary, IReadOnlyCollection) are very underrated and should be used more often than they are being used now in C# code.

You might be wondering what the heck is IReadOnlyCollection? I’ll try to keep it simple and will explain the usefulness of this with an example.

Assume that you’re creating an application that shows student's data, and you’re using a repository pattern, so at a bare minimum, you’ll have,

  1. Student Model
  2. Student Repository (Which’ll return Students)

When you want all the students you’ll return List<Student> or IList<Student>your method may look something like this.

Now assume the scenario where you are working in a pretty big team where you’re responsible for writing data access layer, someone else for business logic, and a third developer will consume that, what if that developer will try to add a new item to the list, or you want to prevent yourself from adding an item to the list? you can use IReadOnlyListhow?

Notice the change in the method signature in both the example, we changed the return type from List<Student> to IReadOnlyList<Student>

See how Add method is not available

but it’s available for a method which is returning List<Student>, like

Otherwise, it’ll behave like a normal List<T>

IReadOnlyList<T> is an interface that is implemented by List<T> , so it works.

Side Note: IReadOnlyList<T> doesn't stop someone from modifying the items within the list e.g. list[0].Id=2;

Note: this is not a security feature, anyone can cast IReadOnlyList<T> back to List<T> so DON'T depend too much on it, this is just a good check (and practice perhaps.)

The same way you can use other IReadonlycollections listed below,

  1. IReadOnlyList
  2. IReadOnlyDictionary
  3. IReadOnlyCollection

Code is from a demo GitHub repository which you can check out here.

Conclusion

it’s good practice to mark your lists as ReadOnly which shouldn't take new items. and as a developer, you should use it whenever you can.