Object reference not set to an instance of an object - What it means and why it happens.

  • Updated

We have all ran into the dreaded NullReferenceException i.e. "Object Reference not sent to and instance of an object" error when browsing to a page or occasionally find one when looking through our event viewer logs. But what does this exactly mean?

Typically means the reference is null, and you cannot access an object through a null reference. The simplest case:

long contentID = 8888;
var _contentManager = new Ektron.Cms.Framework.Content.ContentManager();
Ektron.Cms.ContentData _contentdata = _contentManager.GetItem(contentID);
contentdata.Title = "New Title";
_contentManager.Update(_contentdata);

Object Ref

 

In this example using the content manager we try and retrieve a single content item and update the title. However the content id was supposed to be 888 not 8888. Meaning we were trying to update the title of a content item that does not exist. So essentially we have referenced content Data (the object) that is not set to an existing content item (an instance of an object). Now this can happen if the content item is archived or in a bad state. It can also happen to not just to content but with a variety of other data so it is always good to understand what this error means.