Your best bet would be to use an ObservableCollection<T>
or BindingList<T>
to get push notification of a change. You could also subclass Collection<T>
if you want any custom behaviour.
To answer your question as asked (except for the cpu-intensive bit), you can use an existing feature of List<T>
: it maintains its own version internally so that it can throw if the collection has changed during enumeration.
This is based on analyzing code from reflector. It is not part of any contract, so it is liable to break at any time. It may also not work in a partial-trust environment. Please use with care:
public static int GetVersion<T>(this List<T> list)
{
return (int)list.GetType()
.GetField("_version", BindingFlags.Instance | BindingFlags.NonPublic)
.GetValue(list);
}
...
private int _lastCheckedVersion = 0;
private void Update()
{
int currentVersion = ourList.GetVersion();
if(currentVersion != _lastCheckedVersion) CheckList(ourList);
_lastCheckedVersion = currentVersion;
}