Object reference not set to an instance of an object

As a developer lot of time, you come across ” Object reference not set to an instance of an object ” error and sometimes along with the yellow screen of death. This error is very generic and does not give you a lot of information on what went wrong. In this blog, let’s explore different ways to analyse and fix this error.

The main cause of this error is; the object or resource your code is looking for does not exists. Now it could be deleted, does not get initialized or an object or resource is moved to a different location.

c# Object reference not set to an instance of an object
c# Object reference not set to an instance of an object

Investigation & Fix: Object reference not set to an instance of an object

Application Logs

Every good web application record error or warning logs. If you explore these logs you will able to see which page or object is problematic.

There are lot of tools available to help you record these logs in your code. You do not need to choose any one of these. These tools are made to make your life easier.

  • log4net
  • elmah
  • more ….

Event Viewer

If you have access to the webserver or application server then your first option is to go to the event viewer and look at the application error logs. These logs will give you a hint on what page or class you have an error in. These logs also tell you about the problematic object.

Application Insight

For application hosted in Azure cloud, Application insight is the best tool to analyse and investigate Object reference errors.

Application insight is a very powerful tool in Azure that will give true insight performance of your application.

This tool has a feature “Failed requests”. This feature gives you list of all errors on your website. If you explore further more, you can also check exception against each error, user request map and telemetry of how application is interacting with different layers (for example database layer).

About the author

Naveed Ul-Haq

I am a UK based technical architect. I love working with .NET based CMS, eCommerce solutions, .NET Core, DevOps, and Cloud computing. I am a Certified Episerver CMS developer, MCSD (Microsoft Certified Solution Developer) and MCP in Azure application development. I spend my free time with my family and reading books. You can contact me on [email protected]

View all posts

Leave a Reply

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