debugcsharpCritical
What is a NullReferenceException, and how do I fix it?
Viewed 0 times
fixnullreferenceexceptionhowandwhat
Problem
I have some code and when it executes, it throws a
Object reference not set to an instance of an object.
What does this mean, and what can I do to fix this error?
NullReferenceException, saying:Object reference not set to an instance of an object.
What does this mean, and what can I do to fix this error?
Solution
What is the cause?
Bottom Line
You are trying to use something that is
Like anything else,
Note that accessing it via
The rest of this article goes into more detail and shows mistakes that many programmers often make which can lead to a
More Specifically
The
This means the reference is
This will throw a
Debugging
How do you find the source of a
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 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.
Examples
Some common scenarios where the exception can be thrown:
Generic
If ref1 or ref2 or ref3 is null, then you'll get a
Specifically, in
Indirect
If you want to avoid the child (Person) null reference, you could initialize it in the parent (Book) object's constructor.
Nested Object Initializers
The same applies to nested object initializers:
This translates to:
While the
Nested Collection Initializers
The nested collection
This translates to:
`Person
Bottom Line
You are trying to use something that is
null (or Nothing in VB.NET). This 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".null can have different meanings:- Object variables that are uninitialized and hence point to nothing. In this case, if you access members of such objects, it causes a
NullReferenceException.
- The developer is using
nullintentionally to indicate there is no meaningful value available. Note that C# has the concept of nullable datatypes for variables (like database tables can have nullable fields) - you can assignnullto them to indicate there is no value stored in it, for exampleint? a = null;(which is a shortcut forNullable a = null;) where the question mark indicates it is allowed to storenullin variablea. You can check that either withif (a.HasValue) {...}or withif (a==null) {...}. Nullable variables, likeain this example, allow to access the value viaa.Valueexplicitly, or just as normal viaa.
Note that accessing it via
a.Value throws an InvalidOperationException instead of a NullReferenceException if a is null - you should do the check beforehand, i.e. if you have another non-nullable variable int b; then you should do assignments like if (a.HasValue) { b = a.Value; } or shorter if (a != null) { b = a; }.The rest of this article goes into more detail and shows mistakes that many programmers often make which can lead to a
NullReferenceException.More Specifically
The
runtime throwing a NullReferenceException always means the same thing: you are trying to use a reference, and 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 (such as methods) 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.Debugging
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 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.
Examples
Some common scenarios where the exception can be thrown:
Generic
ref1.ref2.ref3.member
If ref1 or ref2 or ref3 is null, then you'll get a
NullReferenceException. If you want to solve the problem, then find out which one is null by rewriting the expression to its simpler equivalent:var r1 = ref1;
var r2 = r1.ref2;
var r3 = r2.ref3;
r3.member
Specifically, in
HttpContext.Current.User.Identity.Name, the HttpContext.Current could be null, or the User property could be null, or the Identity property could be null.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.
Nested Object Initializers
The same applies to nested object initializers:
Book b1 = new Book
{
Author = { Age = 45 }
};
This translates to:
Book b1 = new Book();
b1.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 property is still null.Nested Collection Initializers
public class Person
{
public ICollection Books { get; set; }
}
public class Book
{
public string Title { get; set; }
}
The nested collection
Initializers behave the same:Person p1 = new Person
{
Books = {
new Book { Title = "Title1" },
new Book { Title = "Title2" },
}
};
This translates to:
`Person
Code Snippets
Person[] people = new Person[5];
people[0].Age = 20 // people[0] is null. The array was allocated but not
// initialized. There is no Person to set the Age for.Context
Stack Overflow Q#4660142, score: 2744
Revisions (0)
No revisions yet.