Object reference not set to an instance of an object? What is a NullReferenceException

What is the reason for the error Object reference not set to an instance of an object? What is a NullReferenceException? let us see here.

Here it is..

You are trying to use something that is null . That means you either set it to null, or you never set it to anything at all.

Like anything else, null gets passed around. If it is null in method “A”, it could be that method “B” passed a null to method “A”.

The rest of this article goes into more detail and shows mistakes that many programmers often make which can lead to a NullReferenceException.The runtime throwing a NullReferenceException always means the same thing: you are trying to use a reference. The reference is not initialized (or it was once initialized, but is no longer initialized).

This means the reference is null, and you cannot access members through a null reference. The simplest case:

string foo = null;
foo.ToUpper();
This will throw a NullReferenceException at the second line because you can’t call the instance method ToUpper() on a string reference pointing to null.

How do you find the source of a NullReferenceException? Apart from looking at the exception itself, which will be thrown exactly at the location where it occurs, the general rules of debugging in Visual Studio apply: place strategic breakpoints and inspect your variables, either by hovering the mouse over their names, opening a (Quick)Watch window or using the various debugging panels like Locals and Autos.

If you want to find out where the reference is or isn’t set, right-click its name and select “Find All References”. You can then place a breakpoint at every found location and run your program with the debugger attached. Every time the debugger breaks on such a breakpoint, you need to determine whether you expect the reference to be non-null, inspect the variable and and verify that it points to an instance when you expect it to.

By following the program flow this way, you can find the location where the instance should not be null, and why it isn’t properly set.

Class instances

When creating a variable of a reference (class) type, it is by default set to null.

public class Book {
public string Title { get; set; }
}
public class Example {
public void Foo() {
Book b1;
string title = b1.Title; // You never initialized the b1 variable.
// there is no book to get the title from.
}
}
Class type variables must either be initialized or set to an already existing class instance. Initialization is done by using the new keyword.

Book b1 = new Book();
Indirect

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; // You never initialized the Author property.
// there is no Person to get an Age from.
}
}
If you want to avoid the child (Person) null reference, you could initialize it in the parent (Book) object’s constructor.

The same applies to nested object initializers:

Book b1 = new Book { Author = { Age = 45 } };
While the new keyword is used, it only creates a new instance of Book, but not a new instance of Person, so the Author the property is still null.

public class Person {
public string Name { get; set; }
}
var people = new List<Person>();
people.Add(null);
var names = from p in people select p.Name;
string firstName = names.First(); // Exception is thrown here, but actually occurs
// on the line above. “p” is null because the
// first element we added to the list is null.
Events

// if the “FirstName” session value has not yet been set,
// then this line will throw a NullReferenceException
string firstName = Session[“FirstName”].ToString();
ASP.NET MVC empty view models

If the exception occurs when referencing a property of @Model in an ASP.NET MVC view, you need to understand that the Model gets set in your action method, when you return a view. When you return an empty model (or model property) from your controller, the exception occurs when the views access it:

<p>@Model.somePropertyName</p> <!– Also throws –>
WPF Control Creation Order and Events

WPF controls are created during the call to InitializeComponent in the order they appear in the visual tree. A NullReferenceException will be raised in the case of early-created controls with event handlers, etc. , that fire during InitializeComponent which reference late-created controls.

<!– Label declared later –>
<Label Name=”label1″
Content=”Label”
Margin=”10″ />
</Grid>
Here comboBox1 is created before label1. If comboBox1_SelectionChanged attempts to reference `label1, it will not yet have been created.

You can also throw a custom exception, only to catch it in the calling code:

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;
}
Use Debug.Assert if a value should never be null, to catch the problem earlier than the exception occurs.

When you know during development that a method maybe can, but never should return null, you can use Debug.Assert() to break as soon as possible when it does occur:

string GetTitle(int knownBookID) {
// You know this should never return null.
var book = library.GetBook(knownBookID);

// Exception will occur on the next line instead of at the end of this method.
Debug.Assert(book != null, “Library didn’t return a book for known book ID.”);

// Some other code

return book.Title; // Will never throw NullReferenceException in Debug mode.
}
Though this check will not end up in your release build, causing it to throw the NullReferenceException again when book == null at runtime in release mode.

Use GetValueOrDefault() for nullable value types to provide a default value when they are null.

// Note that the above “GetValueOrDefault()” can also be rewritten to use
// the coalesce operator:
serviceImpl.FrobPowerLevel = frobPowerLevel ?? 5;
}
Use the null condition operator: ?. (available in C# 6 and VB.NET 14):

This is also sometimes called the safe navigation or Elvis (after its shape) operator. If the expression on the left side of the operator is null, then the right side will not be evaluated, and null is returned instead. That means cases like this:

var title = person.Title.ToUpper();
If the person does not have a title, this will throw an exception because it is trying to call ToUpper on a property with a null value.

In C# 5 and below, this can be guarded with:

var title = person.Title == null ? null : person.Title.ToUpper();
Now the title variable will be null instead of throwing an exception. C# 6 introduces a shorter syntax for this:

var title = person.Title?.ToUpper();
This will result in the title variable being null, and the call to ToUpper is not made if person.Title is null.

Of course, you still have to check title for null or use the null condition operator together with the null coalescing operator (??) to supply a default value: