Why do List<T>, Dictionary<T> and others collections contain a field called "version"?

381 views Asked by At

I was looking at the source code reference for C# and in some collections I found:

int _version = 0;

Each time the collection changes the version increases.

Whats the point of that field?

Dictionary

List

Stack

1

There are 1 answers

0
Kyle On BEST ANSWER

Looking at the source here it seems to be used to check if the state has changed and causes the internal Enumerator to throw an InvalidOperationException when enumerating. This also applies to the List<T>.ForEach(..) method.

This makes sense because it's not legal to modify collections while they are being enumerated. More accurately, it's not legal to continue to iterate a collection once it's been modified, but I find the former rule saves me from running into the latter.