Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying a built-in .NET collection int.MaxValue times and more - potential overflow error

Back in time when .NET Reflector was free I used it to gasp into the .NET framework code. It came to my attention that most collections in .NET 2.0 (I believe this is applicable for current versions too) use the following mechanism to recognize collection modifications during loops:

public class SomeCollection<T>
{
    internal int version = 0;

    // code skipped for brevity

    public void Add(T item)
    {
        version++;

        // add item logic ...
    }

    public IEnumerator<T> GetEnumerator()
    {
         return new SomeCollectionEnumerator<T>(this);
    }
}

public class SomeCollectionEnumerator<T> : IEnumerator<T>
{
     private SomeCollection<T> collection;
     private int version;

     public SomeCollectionEnumerator(SomeCollection<T> collection)
     {
         this.version = collection.version;
         this.collection = collection;
     }

     public bool MoveNext()
     {
         if (this.version != this.collection.version)
         {
             // collection was modified while iterated over
             throw SomeException(...);
         }
         // iteration logic here...
     }
}

Now imagine the hypothetical case of a long running application (a heavily used web service that must have minimal downtime and should be stable and reliable) that keeps a given collection instance (one of the built-in collection types in .NET framework) in memory for as long as it runs. The collection gets modified frequently enough so that int.MaxValue modifications are possible to happen. Is there a risk that the version++ line in every modification method of the collection throws an overflow exception (assuming the overflow checks are not globally disabled).

I must admit that I have weak memories of the details of the reflected code, but I do not remember usage of unckecked blocks around version++ operations. Does this mean built-in collection types in .NET are not suitable for the purpose of such long-time running application scenario? Just out of curiosity, has someone encountered a real-life scenario where this could actually happen?

like image 282
Ivaylo Slavov Avatar asked Oct 06 '22 23:10

Ivaylo Slavov


1 Answers

No, because the c# compiler makes integer arithmetic unchecked by default. (This includes the compiled BCL.)

like image 199
Michael Graczyk Avatar answered Oct 10 '22 13:10

Michael Graczyk