We're launching a system, and we sometimes get the famous exception NullReferenceException with the message Object reference not set to an instance of an object.

However, in a method where we have almost 20 objects, having a log which says an object is null, is really of no use at all. It's like telling you, when you are the security agent of a seminar, that a man among 100 attendees is a terrorist. That's really of no use to you at all. You should get more information, if you want to detect which man is the threatening man.

Likewise, if we want to remove the bug, we do need to know which object is null.

Now, something has obsessed my mind for several months, and that is:

Why doesn't .NET give us the name, or at least the type of the object reference, which is null?. Can't it understand the type from reflection or any other source?

Also, what are the best practices to understand which object is null? Should we always test nullability of objects in these contexts manually and log the result? Is there a better way?

Update: The exception The system cannot find the file specified has the same nature. You can't find which file, until you attach to the process and debug. I guess these types of exceptions can become more intelligent. Wouldn't it be better if .NET could tell us c:\temp.txt doesn't exist. instead of that general message? As a developer, I vote yes.

  • 14
    The exception should include a stack trace with line number. I would start my investigation from there looking at every object accessed on that line. – PersonalNexus Jan 15 '12 at 11:25
  • 2
    Also, I've always wondered why the exception helper dialog in Visual Studio includes the "helpful" hint to use new to create instances of a class. When does such a hint every really help? – PersonalNexus Jan 15 '12 at 11:27
  • 1
    If you have a chain of ten object calls then you've got a problem with coupling in your design. – Pete Kirkham Feb 11 '13 at 9:32
  • 4
    see this question stackoverflow.com/questions/14787580/… – user78203 Feb 12 '13 at 8:15
  • 9
    I love how every single answer to this question are along the lines of "Use a debugger, log your errors, check for null, it's your fault anyway" which are not answering the question but putting the blame on you. Only on stackoverflow does someone actually give you an answer (which I think says it's too much overhead for the VM to keep track of). But really, the only people who can answer this question properly is someone from microsoft who worked on the framework. – Rocklan Feb 20 '13 at 23:19

The NullReferenceException basically tells you: you are doing it wrong. Nothing more, nothing less. It's not a full-fledged debugging tool, on the contrary. In this case I'd say you're doing it wrong both because

  • there is a NullReferenceException
  • you didn't prevent it in a way you know why/where it happened
  • and also maybe: a method requiring 20 objects seems a bit off

I'm a big fan of checking everything before things start going wrong, and providing good information to the developer. In short: write checks using ArgumentNullException and the likes and write the name yourself. Here's a sample:

void Method(string a, SomeObject b)
    if (a == null) throw ArgumentNullException("a");
    if (b == null) throw ArgumentNullException("b");

    // See how nice this is, and what peace of mind this provides? As long as
    // nothing modifies a or b you can use them here and be 100% sure they're not
    // null. Should they be when entering the method, at least you know which one
    // is null.
    var c = FetchSomeObject();
    if(c == null)
        throw InvalidOperationException("Fetching B failed!!");

    // etc.

You could also look into Code Contracts, it has it quirks but it works pretty well and saves you some typing.

  • 17
    @SaeedNeamati you are not implying that because you have a large codebase you should not do decent error checking, right? Imo the larger the project, the more important become the roles or error checking and reporting. – stijn Jan 15 '12 at 12:54
  • 6
    +1 for good advice, even if it doesn't answer the actual question (which probably only Anders Hejlsberg can answer). – Ross Patterson Jan 15 '12 at 15:09
  • 12
    +1 for excellent advice. @SaeedNeamati you should listen to this advice. Your problem is caused by carelessness and a lack of professionalism in the code. If you don't have time to write good code, you have much bigger problems... – MattDavey Oct 26 '12 at 9:49
  • 3
    If you don't have time to write good code, then you definitely don't have time to write bad code. Writing bad code takes longer than writing good code. Unless you really don't care about bugs. And if you really don't care about bugs, why write the program at all? – MarkJ Oct 26 '12 at 12:09
  • 5
    @SaeedNeamati I only say that checking every object to get sure that it's not null, is not a good method Seriously. It's the best method. And not just null, check every argument for reasonable values. The earlier you catch errors, the easier to find the cause. You don't want to have to backtrack several levels in the stack trace to find the causing call. – jgauffin Oct 26 '12 at 12:25

It really should show exactly what you are trying to call. It's like saying "There's a problem. You need to fix it. I know what it is. I'm not going to tell you. You go figure it out" Bit like half the answers on this Stack Overflow, ironically.

So how useful would it be, for example, if you got this...

Object reference (HttpContext.Current) not set to instance of an object

...? To have to go into the code, step through it, and work out that the thing you are trying to call is null is fine, but why not just give us a little helping hand?

I agree that it is usually useful to step through the code to get to the answer (because you will probably find out more), but often a lot of time and frustration would be saved if the NullReferenceException text was more like the example above.

Just sayin.


Your log should include a stack trace - that usually gives you a hint as to which line in the method has the problem. You may need to make your release build include PDB symbols so you have an idea which line the error is on.

Granted, it won't help you in this case:


The tell don't ask principle can help to avoid such code.

As to why the information isn't included, I'm not sure - I suspect that at least in a debug build, if they really wanted to, they could figure it out. Taking a crash dump and opening in WinDBG may help.


Exceptions have been created as a tool to signal exceptional non-fatal conditions up the call chain. That is, they are not designed as a debugging tool.

If a null-pointer exception were a debugging tool, it would abort program execution right on the spot, allowing a debugger to connect, pointing it right at the incriminating line. This would give the programmer all the context information that is available. (Which is pretty much what a Segfault due to a null pointer access does in C, albeit a bit crudely.)

However, the null-pointer exception is designed as a valid runtime condition that can be thrown and caught in normal program flow. Consequently, performance considerations need to be taken into account. And any customization of the exception message requires string objects being created, concatenated, and destroyed at runtime. As such, a static message is undisputably faster.

I'm not saying that the runtime could not be programmed in a way that would yield the name of the incriminating reference, though. That could be done. It would just make exceptions even slower than they are. If anyone cared enough, such a feature could even be made switchable, so that it would not slow down production code, but allow for easier debugging; but for some reason nobody seems to have cared enough.


Cromulent hit the nail on the head I think, however there is the obvious point too that if you're getting a NullReferenceException you have uninitialised variable(s). The argument that you have circa 20 objects being passed into a method cannot be said to be a mitigation: as the creator of a chunk of code you have to be responsible for its doings, that includes its compliance to the rest of a codebase, as well as proper and correct utilisation of variables etc.

it is onerous, tedious and sometimes dull, but the rewards at the end are worth it: many are the times when I have had to trawl through log files weighing in at several gigabytes, and they are almost always helpful. However before you get to that stage, the debugger can help you, and before that stage good planning will save a lot of pain(and I do not mean a fully engineered approach to you code solution either: simple sketches and some notes can and will be better than nothing).

In regards to the Object reference not set to an instance of an object the code cannot guess at values we may like: that's our job as programmers, and it simply means you have passed an uninitialised variable in.

  • You realize people used to offer justifications like this for writing in assembly language? And not using automatic garbage collection? And being able to do arithmetic - in hex? "onerous, tedious and sometimes dull" is how we describe jobs that should be automated. – Spike0xff Sep 28 '15 at 20:34

Learn to use the debugger. This is exactly the kind of thing it is designed for. Set a break point on the method in question and away you go.

Simply step through your code and see exactly what the values of all your variables are at certain points.

Edit: Frankly I'm shocked that no one else has mentioned using the debugger yet.

  • 2
    So you are saying that all exceptions can easily be reproduced when using a debugger? – jgauffin Feb 20 '13 at 11:54
  • @jgauffin I'm saying that you can use a debugger to see why an exception is being thrown in real world code rather than synthetic unit tests that might not actually fully test the code in question or the unit tests themselves may have bugs in which causes them to miss bugs in the real code. A debugger trumps just about any other tool I can think of (except perhaps things like Valgrind or DTrace). – Cromulent Feb 20 '13 at 12:11
  • 1
    So you are saying that we always have access to the failing computer and that debugging is better than unit tests? – jgauffin Feb 20 '13 at 12:17
  • @jgauffin I'm saying if you have a choice then go with the debugger in preference to other tools. Of course if you don't have that choice then it is a bit of a non-starter. Clearly this is not the case with this question which is why I gave the answer I did. If the question had been how do you fix this issue on a clients computer with no way to do remote debugging (or local debugging) my answer would have been different. You seem to be trying to warp my answer in ways which have no relevance to the question at hand. – Cromulent Feb 20 '13 at 17:14

If you wanted to go with @stijn's answer and put null checks in your code, this code snippet should help. Here's some info about code snippets. Once you have this set up, just type argnull, hit tab twice, and then fill in the blank.

<CodeSnippet Format="1.0.0">
        <ToolTip>The name of the argument that shouldn't be null</ToolTip>
    <Code Language="CSharp">
      <![CDATA[if ($argument$ == null) throw new ArgumentNullException("$argument$");$end$]]>
  • note: c#6 now has nameof so your snippet could be throw new ArgumentNullException(nameof($argument$)) which has the advantages of not including magic constants, being checked by the compiler, and working better with refactoring tools – stijn Aug 22 '15 at 7:55

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