What is NullReferenceException and how can I fix the code?

When I execute some code, a NullReferenceException is thrown with the following message:

Object reference not set to an instance of an object.


Object reference not set to an instance of an object.

What does this mean and how can I fix the code?


You are trying to use something that is null (or Nothing in VB.NET). This means that either you have assigned this value, or you have not assigned anything.

Like any other value, null can be passed from object to object, from method to method. If something is null in method “A”, it may well be that method “B” passed that value to method “A”.

The rest of the article describes what’s going on in detail and lists common errors that can result in a NullReferenceException.

In details
If the runtime throws a NullReferenceException, it always means one thing: you are trying to use a reference. And this reference is not initialized (or was initialized, but not already initialized).

This means that the reference is null, and you cannot call methods through a null reference. In the simplest case:

string foo = null;
This code will throw a NullReferenceException on the second line because you can’t call the ToUpper() method on a string reference that is null.

How to determine the source of the error? In addition to examining the actual exception that will be thrown exactly where it occurred, you can use the general debugging tips in Visual Studio: set breakpoints at key points, examine the values ​​of variables, either by hovering the mouse cursor over the variable, or by opening panels for debugging: Watch, Locals, Autos.

If you want to determine where a reference’s value is set or not set, right-click on its name and select “Find All References”. You can then put breakpoints on each line found and run the application in debug mode. Every time the debugger hits a breakpoint, you can make sure the value is correct.

By following the progress of the program, you will come to a place where the value of the reference should not be null, and determine why the correct value was not assigned.

Some common examples where an exception occurs.

If ref1, ref2, or ref3 is null, you will get a NullReferenceException. To solve the problem and determine what exactly is null, you can rewrite the expression in a simpler way:

varr1 = ref1;
var r2 = r1.ref2;
var r3 = r2.ref3;
For example, in the HttpContext.Current.User.Identity.Name chain, both HttpContext.Current, User, and Identity may not have a value.

public class person {
public int Age { get; set; }
public class Book {
public Person Author { get; set; }
public class Example {
public void Foo() {
Book b1 = new Book();
int authorAge = b1.Author.Age; // The Author property has not been initialized
// there is no Person from which Age can be calculated.
The same is true for nested initializers:

Book b1 = new Book { Author = { Age = 45 } };
Despite the use of the new keyword, only an instance of the Book class is created, but no Person instance is created, so the Author property remains null.

int[] numbers = null;
int n = numbers[0]; // numbers = null. No array to get element by index
Array elements
Person[] people = new Person[5];
people[0].Age = 20; // people[0] = null. The array is created but not
// initialized. There is no Person that can be set Age.
array of arrays
long[][] array = new long[1][];
array[0][0] = 3; // = null because only the first dimension is initialized.
// First do array[0] = new long[2].
Dictionary<string, int> agesForNames = null;
int age = agesForNames[“Bob”]; // agesForNames = null.
// Dictionary instance not created.
public class person {
public string Name { get; set; }
var people = new List<Person>();
var names = from p in people select p.Name;
string firstName = names.First(); // Exception is thrown here even though it is being thrown
// line above. p = null because
// first added element = null.
public class Demo
public event EventHandler StateChanged;

protected virtual void OnStateChanged(EventArgs e)
StateChanged(this, e); // An exception will be thrown here if
// no one subscribed to the StateChanged event
Unsuccessful variable naming
If in the code below the local variables and fields had different names, you would find that the field was not initialized:

public class Form1 {
private customer customer;

private void Form1_Load(object sender, EventArgs e) {
Customer customer = new Customer();
customer.Name = “John”;

private void Button_Click(object sender, EventArgs e) {
You can avoid the problem if you use a prefix for the fields:


Оцените статью
Добавить комментарий

Your email address will not be published. Required fields are marked *