Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have some code and when it executes, it throws a NullReferenceException, saying, "Object reference not set to an instance of an object.".

What does this mean, and what can I do about it?

share|improve this question
11  
Care to explain how your MVP profile states "John Saunders is a .NET developer who has worked with the technology since the early beta versions"? Surely you understand what exceptions are? – m.edmondson Jan 11 '11 at 16:55
54  
@m.edmondson: I think it means John is more than totally fed up with people asking the same question over and over again, phrased in slightly different, obfuscated ways, where the answer in the end is always the same ;) This is the most basic, most elementary phrased question that will provide the answer, so it's bound to be found more easily. – Willem van Rumpt Jan 11 '11 at 16:59
10  
@Willem: thanks. That's the purpose. I've known about NullReferenceException since the earliest pre-betas of .NET 1.0. – John Saunders Jan 11 '11 at 17:00
3  
@m.edmonson - I am pretty sure that John does know about exceptions. He is creating this question, and subsequent answer, so that it is easier for people searching to find the answer. This is to hopefully prevent further questions on NullReferenceExceptions appearing. – Barry Jan 11 '11 at 17:01
6  
@Barry: I don't mind all the answers, as they are similarly simple. My goal is that, whenever someone posts some complicated code and says, "it gets NullReferenceException", I will vote to close as a duplicate of this one. – John Saunders Jan 11 '11 at 17:14
show 8 more comments

9 Answers

It means your code used an object reference that was set to null (i.e. it did not refer to an actual object instance).

To prevent the error, objects that could be null should be tested for null before being used.

share|improve this answer

It means that the variable in question is pointed at nothing. I could generate this like so:

SqlConnection connection = null;
connection.Open();

That will throw the error because while I've declared the variable "connection", it's not pointed at anything. When I try to call the member "Open", there's no reference for it to resolve, and it will throw the error.

To avoid this error:

  1. Always initialize your objects before you try to do anything with them...
  2. If you're not sure whether the object is null, check it with object == null.

JetBrains' Resharper tool will identify every place in your code that has the possibility of a null reference error, allowing you to put in a null check. This error is the number one source of bugs, IMHO.

share|improve this answer
2  
Your example won't generate a NullReferenceException because it won't compile in the first place (assuming that connection is a local variable and not a field). – LukeH Jan 11 '11 at 16:54
@LukeH That will indeed compile... – Aaron McIver Jan 11 '11 at 17:08
1  
I corrected it after his comment. – Chris B. Behrens Jan 11 '11 at 17:12
up vote 142 down vote accepted

NullReferenceException always means the same thing. You are trying to use a reference to an object, but you haven't initialized it (or it used to be initialized, but is now uninitialized).


Examples

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:

   var r1 = ref1;
   var r2 = r1.ref2;
   var r3 = r2.ref3;
   r3.member

You can step through your code with the debugger to see which is null, or just let it run, and the exception message will tell you which of those lines is the culprit.

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.

Simple

string s1 = null;
int len = s1.Length; // s1 is null. There is no string to get a length from.

Indirect

public class Person {
    public int Age { get; set; }
}
public class Book {
    public Person Author { get; set; }
}
Book b1 = new Book();
int authorAge = b1.Author.Age; // You never initialized the Author property.
                               //  there is no Person to get an Age from.

Array

int[] numbers = null;
int n = numbers[0]; // numbers is null.  There is no array to index.

Array Elements

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.

Collection/List/Dictionary

Dictionary<string, int> agesForNames = null;
int age = agesForNames["Bob"]; // agesForNames is null.
                               // There is no Dictionary to perform the lookup.

Range Variable (Indirect/Deferred)

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.

Bad Naming Conventions:

public class Form1 {
    private Customer customer;

    private void Form1_Load(object sender, EventArgs e) {
        Customer customer = new Customer();
        customer.Name = "John";
    }

    private void Button_Click(object sender, EventArgs e) {
        MessageBox.Show(customer.Name);
    }
}

If you named fields differently from locals, you might have realized that you never initialized the field. Suggestion:

private Customer _customer;

ASP.NET Page Life cycle:

public partial class Issues_Edit : System.Web.UI.Page
{
    protected TestIssue myIssue;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            myIssue = new TestIssue(); // Only called on first load, not when button clicked
        }
    }

    protected void SaveButton_Click(object sender, EventArgs e)
    {
        myIssue.Entry = "NullReferenceException here!";
    }
}

ASP.NET Session Values

// if the "FirstName" session value has not yet been set,
// then this line will throw a NullReferenceException
string firstName = Session["FirstName"].ToString();

Ways to Avoid

Explicitly check for null, and ignore null values.

void PrintName(Person p) {
    if (p != null) {
        Console.WriteLine(p.Name);
    }
}

Explicitly check for null, and provide a default value.

string GetCategory(Book b) {
    if (b == null)
        return "Unknown";
    return b.Category;
}

Explicitly check for null, and throw a more meaningful 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;
}

Use Debug.Assert if a value should never be null, to catch the problem earlier.

string GetTitle(int knownBookID) {
    var book = library.GetBook(knownBookID);  // Should never return null
    // Exception will occur on the next line instead of 3 lines down
    Debug.Assert(book != null, "Library did not return a book for known book ID.");
    // Some other code ...
    return book.Title; // Will never throw NullReferenceException in Debug mode
}

Use GetValueOrDefault() for nullable objects to provide a default value when null is encountered.

DateTime? appointment = null;
Console.WriteLine(appointment.GetValueOrDefault(DateTime.Now));
//Will display the Default value provided because appointment is null

appointment = new DateTime(2022, 10, 20);
Console.WriteLine(appointment.GetValueOrDefault(DateTime.Now));
//Will display the appointment date, not the default

Use the null coalescing operator: ?? [C#] or If() [VB].

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;
}
share|improve this answer
13  
@John Saunders, not to be super critical but this is such a basic question that if someone is searching for it they need a really, really basic answer. I'd recommend changing your classes from abstract A's and B's into concrete things like Person and Employee or something similar. Probably have a VB version, too. – Chris Haas Jan 11 '11 at 17:15
3  
@Chris: constructive criticism is welcome. I also want an array example. – John Saunders Jan 11 '11 at 17:17
9  
@Chris: worth noting that he made this answer CW... If you have something to contribute, you should consider editing it. – Shog9 Jan 11 '11 at 19:36
1  
I added the "array elements" example, inspired by stackoverflow.com/q/4660103 – Justin Jan 13 '11 at 21:37
3  
@Random832 I'd also add that although a try block is free, exceptions are incredibly expensive and involve unwinding the stack - so they should be kept to an absolute minimum and never as part of the intended application flow – Basic Dec 21 '12 at 18:22
show 7 more comments

Note, regardless of the scenario, the cause is always the same in .NET:

You are trying to use a reference variable who’s value is Nothing/null. When the value is Nothing/null for the reference variable, that means it is not actually holding a reference to an instance of any object that exists on the heap. You either never assigned something to the variable, never created an instance of the value assigned to the variable, or you set the variable equal to Nothing/null manually, or you called a function that set the variable to Nothing/null for you.

share|improve this answer

An example of this exception being thrown is; when you are trying to check something, that is null.

for example:

string testString = null; //because it doesn't have a value (i.e. it's null, "Length" cannot do what it needs to do)

if(testString.Length == 0) // throws a nullreferenceexception
{
//do something
} 

Other peoples code (e.g. code inside the .net framework) may throw a NullReferenceException, where the code cannot do what it needs to if your code sets it to null i.e. it expects something other than null.

More info here: http://dotnetperls.com/nullreferenceexception

share|improve this answer
7  
Other people's code is not "allowed" to throw a NullReferenceException: that is a bug, no excuses. Code that expects non-null values should refuse them with ArgumentNullException. – R. Martinho Fernandes Feb 18 '11 at 1:26
@Martinho Fernandes - interesting point, not thought of it like that. Though I suppose it depends if the exception was thrown due to an argument passed in by the client, or caused by another underlying piece of code... perhaps a net connection broken (for example). – Alex Key Feb 22 '11 at 8:53
6  
No, it does not depend. I said, no excuses. If you pass a null argument, and the underlying code cannot handle it, it must throw ArgumentNullException, not NullReferenceException. A NullReferenceException tells you nothing about the cause of the error. Was it a null argument you passed, or some internal value? You don't want to catch(NullReferenceException) to deal with a broken connection now, do you? The .NET Framework does not throw NREs (except for bugs, of course). It throws ANEs all around. – R. Martinho Fernandes Feb 22 '11 at 9:29
True, a broken connection was a bad example. I didn't realise the .net framework doesn't use NullReferenceExceptions at all. True I understand that if you pass a null, then use a ArgumentNullException. What I mean't was that I thought that there are instances where a NullRefernceException could be used i.e. when not caused by an argument, but by something else within the code. But we're going a little of topic in a comment, thanks for the interesting responses. – Alex Key Feb 22 '11 at 10:46
1  
A NullReferenceException always indicates a bug. You should never be expected to catch a NRE. In my opinion, you should nvever have to catch things like ArgumentNullException either - that also indicates a bug. Other exceptions, like TimeoutException are there to indicate "exceptional" situations, like a connection dropping. Those, you should be specifically catching. – Jonathon Reinhart Mar 5 at 23:17
show 1 more comment

Another case that I don't see mentioned here in the answers is when you cast a null object into a value type. For example, the code below:

    object o = null;
    DateTime d = (DateTime)o;

Will throw a NullReferenceException on the cast. It seems quite obvious in the above sample, but this can happen in more "late-binding" intricate scenarios where the null object has been returned from some code you don't own, and the cast is for example generated by some automatic system.

One example of this is this simple ASP.NET binding fragment with the Calendar control:

<asp:Calendar runat="server" SelectedDate="<%#Bind("Something")%>" />

Here, SelectedDate is in fact a property - of DateTime type - of the Calendar Web Control type, and the binding could perfectly return something null. The implicit ASP.NET Generator will create a piece of code that will be equivalent to the cast code above. And this will raise a NullReferenceException that is quite difficult to spot because it lies in ASP.NET generated code which compiles fine ...

share|improve this answer

you are using the object that contain the null value reference. so its giving null exception. in the example the string value is null and when check its length the exception occured.

Example:

string value = null;
if (value.Length == 0) // <-- Causes exception
{
    Console.WriteLine(value); // <-- Never reached
}

The exception error is:

Unhandled Exception:

System.NullReferenceException: Object reference not set to an instance of an object. at Program.Main()

share|improve this answer

Another case where NullReferenceExceptions can happen is the (incorrect) use of the as operator:

class Book {
    public string Name { get; set; }
}
class Car { }

Car mycar = new Car();
Book mybook = mycar as Book;   // Incompatible conversion --> mybook = null

Console.WriteLine(mybook.Name);   // NullReferenceException

Here, Book and Car are incompatible types; a Car cannot be converted/cast to a Book. When this cast fails, as returns null. Using mybook after this causes a NullReferenceException.

In general, you should use a cast or as, as follows:

If you are expecting the type conversion to always succeed (ie. you know what the object should be ahead of time), then you should use a cast:

ComicBook cb = (ComicBook)specificBook;

If you are unsure of the type, but you want to try to use it as a specific type, then use as:

ComicBook cb = specificBook as ComicBook;
if (cb != null) {
   // ...
}
share|improve this answer

If you have not initialized a Reference Type, and you want to set or read one of its properties, it will throw a NullReferenceException.

Example:

Person p = null;
p.Name = "Harry"; <== NullReferenceException occurs here.

You can simply avoid this by checking if the variable is not null:

Person p = null;
if (p!=null)
{
p.Name = "Harry"; <== not going to run to this point
}

To fully understand why a NullReferenceException is thrown, it is important to know the difference between Value Types and Reference Types.

So, if you're dealing with Value Types, NullReferenceExceptions can not occur. Though you need to keep alert when dealing with Reference Types!

Only Reference Types, as the name is suggesting, can hold references or point literally to nothing (or 'null'). Whereas Value Types always contain a value.

Reference Types: (These ones must be checked)

  • dynamic
  • object
  • string

Value Types: (You can easily ignore these ones)

  • Numeric types
  • Integral types
  • Floating-point types
  • decimal
  • bool
  • User defined structs
share|improve this answer
-1: since the question is "What is a NullReferenceException", value types are not relevant. – John Saunders May 16 at 22:00
@John Saunders: I disagree. As a software developer it is really important to be able to distinguish between value and reference types. else people will end up checking if integers are null. – Fabian Bigler May 16 at 22:28
True, just not in the context of this question. – John Saunders May 16 at 22:44
Thanks for the hint. I improved it a bit and added an example at the top. I still think mentioning Reference & Value Types is useful. – Fabian Bigler May 16 at 23:02
do you still think it's a useless, out of context answer? – Fabian Bigler May 18 at 23:20
show 1 more comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.