user2410832
user2410832

Reputation: 11

Foreach System.NullReferenceException: Object reference not set to an instance of an object

I get System.NullReferenceException: Object reference not set to an instance of an object in this:

var offeredItems = new List<ulong>(Trade.steamMyOfferedItems);
foreach (var item in offeredItems) {
    Trade.RemoveItem(item);
}

What is different than in all such questions is that the exception is in line 3 from this code block. Does it mean that Trade is null? That would be strange because I make this check a few operations earlier:

if (Trade != null && Trade.OtherSID == OtherSID) {
    OnTradeMessage(message);
    return;
}

The only reason for this would be if Trade was nulled in another thread (and that would be very unecxpected behaviour) in time of 5-10 simple operations, this would be really very strange.

EDIT:

The problem is I can't reproduce this doing the exact same steps. I guess Trade has to be null and it has to be nulled in other thread, there is no other option. Sorry for stupid question.

EDIT2:

If Trade.RemoveItem is executed, then offeredItems is not empty, hence Trade cannot be null. In both cases offeredItems should contain 1-2 elements. So as far as I know (and understand):

Trade is not null, Trade is an object of class Trade, which has method RemoveItem (the exception is thrown exactly at this line: Trade.RemoveItem(item);, not in RemoveItem, RemoveItem is not null delegate (this code works most of the time)

Upvotes: 1

Views: 2252

Answers (1)

Sam
Sam

Reputation: 42337

the exception is in line 3 from this code block

Does it mean that Trade is null?

It could mean that. It sounds like one of the following possibilities:

  1. Trade is null.
  2. Trade is a property whose getter throws a NullReferenceException.
  3. RemoveItem is a null delegate.
  4. RemoveItem throws a NullReferenceException.

Why don't you step through the code in a debugger and find out? Also, please see the comments to your question.

Upvotes: 3

Related Questions