How to fix a NullReferenceException error?


The deeper you go in programming, it gets harder and harder. Bugs and errors ruin your code. It is not possible to avoid errors but learning how to fix them will save a lot of time. This is how you can be an expert in programming. Let’s move on to the problem of NullReferenceException error.

How to fix a NullReferenceException error?

The problem

One single mistake and damn, the code will throw an error after execution. One such error is the NullReferenceException error. It will say something like this-

"Object reference not set to an instance of an object."

We will tell you the reason behind the above statement and provide a solution to solve this problem.

What is NullReferenceException error?

NullReferenceException means that the variable is pointing to nothing at all. In other words, your code is using a reference variable whose value is set to Nothing/null. It may possible that you have called a function that has set the variable to Nothing/null. You can also say that your code declared an object variable but it was not instantiated.

For example, the code given below will give the NullReferenceException because one can’t call the instance method ToUpper() on a string reference that point to null.

string foo = null; foo.ToUpper();

The simple solutions to avoid this error are:

  1. Make sure to initialize your objects before you want to perform any operation with them.
  2. Check that the object is null or not with the help of object == null.

Finding the Cause

This error is similar to the NullReference Exception in c#. Both report the same exception which is defined in the .NET framework. To find the cause, take the mouse pointer to the variables in your code. Visual Studio will show the values of all the variables. The one causing the exception will show Nothing.

Solution to avoid and fix the error

  1. Check for null and avoid the null values
  2. Before trying to access instance member, check all the reference if they are null or not. For e.g.

    void PrintName(Person p) { if (p != null) { Console.WriteLine(p.Name); } }
  3. Provide a value to null variable
  4. You have to choose to return a default value because the method call you to expect to return will return null instead of an instance. Look in the following case:

    string GetCategory(Book b) { if (b == null) return "Unknown"; return b.Category; }
  5. Throwing a custom exception
  6. To catch in the calling code, you can try throwing a custom exception,

    string GetCategory(string bookTitle) { var book = library.FindBook(bookTitle); // This may return null if (book == null) throw new BookNotFoundException(bookTitle); // Your custom exception return book.Category; }
  7. Using the null coalescing operator: ?? [C#] or If() [VB] or null condition operator: ?. or ?[x] for arrays
  8. IService CreateService(ILogger log, Int32? frobPowerLevel) { var serviceImpl = new MyService(log ?? NullLog.Instance); // Note that the above "GetValueOrDefault()" can also be rewritten to use // the coalesce operator: serviceImpl.FrobPowerLevel = frobPowerLevel ?? 5; }

Using null condition operator is also called as safe navigation or Elvis operator. When the operator on the left side will be null, then the evaluation of the right side will be performed and null is returned. In the following code, it will throw an exception it is calling ToUpper on a property containing null value.

var title = person.Title.ToUpper();

IN C# 5 and below, you can avoid the NullReferenceException error by using:

var title = person.Title?.ToUpper();

Here, you need to check the title for null and apply the null condition operator null coalescing operator together for providing a default value.

// regular null check int titleLength = 0; if (title != null) titleLength = title.Length; // If title is null, this would throw NullReferenceException // combining the `?` and the `??` operator int titleLength = title?.Length ?? 0;

There are many other ways to solve this problem. It’s all about finding the reason behind the NullReferenceException and avoiding the same mistake again.

Solution Worked 0 UpvotesUpvote


Solution Didn't Worked 0 DownvotesDownvote


Get Programming Help

Play 2048 Game Online

Search Tags