Joaquim Anacleto
Joaquim Anacleto

Reputation: 75

c# ArgumentOutOfRangeException

I Have this piece of code:

    private List<...> LayPrices;
    public Decimal BestLayOdds
    {
        get
        {
            if (LayPrices.Count > 0)
            {
                return LayPrices[0].dOdds;
            }
            return 1000.0M;   
        }
    }

The Problem is that sometimes the List has items, but it does not enter inside the 'if' statement.

Check the images below of a debug session:

enter image description here

How is that even possible?

But if I force it to return the first item, on the last return statement, I get an ArgumentOutOfRangeException even though the list has elements. Check the nest image:

enter image description here

Is there any problem with my code or it is just a stupid bug?

Update:

The LayPrices List is only instantiated on the class Constructor: LayPrices = new List<PriceStruct>();.

It is only getting filled with items on one method, whith the following code:

    LayPrices.Clear();
    foreach (PriceSize priceSize in exchangePrices.availableToLay)
    {
          PriceStruct lay = new PriceStruct();
          lay.dOdds = (Decimal)priceSize.price;
          lay.dAmount = (Decimal)priceSize.size;

          LayPrices.Add(lay);
   }

Concurrency issues and threading were my first clue, so I did put a lock(LayPrices) and the problem still persisted:

lock

So I think it is not a concurrency issue.

Upvotes: 4

Views: 274

Answers (2)

Joaquim Anacleto
Joaquim Anacleto

Reputation: 75

I found the problem. It was indeed concurrency issues, even though I don't use threads explicitly, I use events and I thought event handling was synchronized (It is synchronized right?).

If I add locks everywhere I read or add to the list, the problem disappears.

Upvotes: 1

InBetween
InBetween

Reputation: 32750

Put Debug.Assert(LayPrices.Count > 0) in the getter before the if statement and you'll see that the List is in fact empty.

The only reasonable explanation is that you are populating the list either in some other thread and you have a race condition or in a property getter that only gets fired by the debugger (you could also be populating the list in a catch clause up the callstack but I imagine you would have figured that out by yourself)

In order to get a better answer please include all code that populates your list. No only the code you think should run, but all the properties, constructors or methods that add or remove items from the list.

Upvotes: 2

Related Questions