1

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)

  • 2
    Do you *have* other threads executing that *could* be setting that to null? At any rate, see the related questions list to the right. There are a million of these questions and the solution is the same. Find out what's null and fix it or validate against it. – Anthony Pegram May 31 '13 at 23:56
  • Do you think `item` exist in `Trade`? It might not be found - My guess – codingbiz Jun 01 '13 at 00:05
  • 1
    Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Jun 01 '13 at 00:16
  • Are you able to run the code in a debugger so it pauses execution when the exception is thrown? If so, once it pauses, check the value of `Trade` and other relevant information. This should help you determine what's gone wrong. – Sam Jun 01 '13 at 04:19

1 Answers1

3

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.

Community
  • 1
  • 1
Sam
  • 40,644
  • 36
  • 176
  • 219