Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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

like image 691
Freddx L. Avatar asked Jun 26 '18 22:06

Freddx L.


1 Answers

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.

like image 200
Kyle Avatar answered Nov 14 '22 21:11

Kyle