Search code examples
c#weak-references

What is the proper way to remove items from a List<WeakReference<T>>?


Is the following loop approach, using TryGetTarget then compare the proper way?

void Remove<T>( List<WeakReference<T>> list, T toRemove ) where T : class {
    for(var i=0; i<list.Count; ++i) {
        if(list[i].TryGetTarget(out var el) && el==toRemove) {
            list.RemoveAt(i);
            break;
        }
    }
}

Is there a more elegant or suggested way to do this?


Solution

  • You could probably shorten it to:

    list.RemoveAll(item => item.TryGetTarget(out var el) && el == toRemove);