[Solved-5 Solutions] What is a NullReferenceException, and how do we fix it?
- We have some code and when it executes, it throws a
- Object reference not set to an instance of an object.
- What does this mean, and what can we do to fix this error?
- The runtime throwing a
NullReferenceExceptionalways means the same thing: we are trying to use a reference, and the reference is not initialized (or it was once initialized, but is no longer initialized).
- This means the reference is
null,and we cannot access members (such as methods) through a
nullreference. The simplest case:
- This will throw a
NullReferenceExceptionat the second line because we can't call the instance method
stringreference pointing to
- Since the problem is an object reference which is
Nothing, the answer is to examine them to find out which one. Then determine why it is not initialized. Hold the mouse over the various variables and Visual Studio (VS) will show their values - the culprit will be
- We should also remove any Try/Catch blocks from the relevant code, especially ones where there is nothing in the Catch block. This will cause our code to crash when it tries to use an object which is
Nothing.This is what we want because it will identify the exact location of the problem, and will allow us to identify the object causing it.
- The New operator can often be used to create the instance when you declare it:
- When it is only appropriate to create the instance later:
Note: Do not use Dim again in a procedure, including the constructor (
- Another scenario is when we cast a null object into a value type . For example, the code below:
- It will throw a
NullReferenceExceptionon the cast. It seems quite obvious in the above sample, but this can happen in more "late-binding" intricate scenarios where the null object has been returned from some code we don't own, and the cast is for example generated by some automatic system.
- JetBrains' Resharper tool will identify every place in your code that has the possibility of a null reference error, allowing you to put in a null check.