Null Pointer exception in C#

Null Pointer exception is reported at var async = (AsyncOperation)res.AsyncState;

We can logically deduce that this is not actually the case.

If the line before worked, we know that res is not null. AsyncState is object, so no custom operators are involved here, which means the cast is thus a type-check – which can either return null (without erroring), or can raise an invalid-cast exception.

If you are seeing a NullReferenceException, that leaves 2 options:

  • res is null and it is the line above that is erroring (which: we shouldn’t actually expect – that will not happen)
  • the error is actually coming from EndInvoke, the line after

(the exact line often gets slightly confused when an exception is involved).

I suggest you add logging between each, to track what is happening. I also suggest you explicitly try around the EndInvoke, since that can throw exceptions (it re-throws any exception from the async operation).

In the more general case, a third option would have been:

  • AsyncOperation is a struct, and AsyncState is null

However, in this case we can rule that out by deduction, because if AsyncOperation were a struct, the following would never box to null (only an empty AsyncOperation? would box to null):

AsyncOperation async = AsyncOperationManager.CreateOperation(null);
bkWorker.BeginInvoke(context,completedCallback, async);

Similar Posts