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 to fix this error?
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 to fix this error?
There is a scenario that can happen that is Class related. The question ended up getting closed prior to my stating the resolution: https://stackoverflow.com/questions/43348009/unable-to-instantiate-class
Beware of classes not instantiating: If any part of your constructor in a class throws a
null reference exception
the class does not instantiate. In my case it was trying to get a connection string from the web.config that that did not exist.I instantiated a class:
Inside the class itself was a call to get a connection string from the
web.config
. This part of the constructor threw an null value exception somyClass
was null.If you ever have a situation where a class in not instantiating, try making sure that no part of the class constructor Is throwing a
null value exception
. F-11 and step through the class and make sure there are no nulls.I have a different perspective to answering this. This sort of answers "what else can I do to avoid it?"
When working across different layers, for example in an MVC application, a controller needs services to call business operations. In such scenarios Dependency Injection Container can be used to initialize the services to avoid the NullReferenceException. So that means you don't need to worry about checking for null and just call the services from the controller as though they will always to available (and initialized) as either a singleton or a prototype.
While what causes a NullReferenceExceptions and approaches to avoid/fix such an exception have been addressed in other answers, what many programmers haven't learned yet is how to independently debug such exceptions during development.
In Visual Studio this is usually easy thanks to the Visual Studio Debugger.
First, make sure that the correct error is going to be caught - see How do I allow breaking on 'System.NullReferenceException' in VS2010? Note1
Then either Start with Debugging (F5) or Attach [the VS Debugger] to Running Process. On occasion it may be useful to use
Debugger.Break
, which will prompt to launch the debugger.Now, when the NullReferenceException is thrown (or unhandled) the debugger will stop (remember the rule set above?) on the line on which the exception occurred. Sometimes the error will be easy to spot.
For instance, in the following line the only code that can cause the exception is if
myString
evaluates to null. This can be verified by looking at the Watch Window or running expressions in the Immediate Window.In more advanced cases, such as the following, you'll need to use one of the techniques above (Watch or Immediate Windows) to inspect the expressions to determine if
str1
was null or ifstr2
was null.Once where the exception is throw has been located, it's usually trivial to reason backwards to find out where the null value was [incorrectly] introduced --
Take the time required to understand the cause of the exception. Inspect for null expressions. Inspect the previous expressions which could have resulted in such null expressions. Add breakpoints and step through the program as appropriate. Use the debugger.
1 If Break on Throws is too aggressive and the debugger stops on an NPE in the .NET or 3rd-party library, Break on User-Unhandled can be used to limit the exceptions caught. Additionally, VS2012 introduces Just My Code which I recommend enabling as well.
What can you do about it?
There is a lot of good answers here explaining what a null reference is and how to debug it. But there is very little on how to prevent the issue or at least make it easier to catch.
Check arguments
For example, methods can check the different arguments to see if they are null and throw an
ArgumentNullException
, an exception obviously created for this exact purpose.The constructor for the
ArgumentNullException
even takes the name of the parameter and a message as arguments so you can tell the developer exactly what the problem is.Use Tools
There are also several libraries that can help. "Resharper" for example can provide you with warnings while you are writing code, especially if you use their attribute: NotNullAttribute
There's "Microsoft Code Contracts" where you use syntax like
Contract.Requires(obj != null)
which gives you runtime and compile checking: Introducing Code Contracts.There's also "PostSharp" which will allow you to just use attributes like this:
By doing that and making PostSharp part of your build process
obj
will be checked for null at runtime. See: PostSharp null checkPlain Code Solution
Or you can always code your own approach using plain old code. For example here is a struct that you can use to catch null references. It's modeled after the same concept as
Nullable<T>
:You would use very similar to the same way you would use
Nullable<T>
, except with the goal of accomplishing exactly the opposite - to not allownull
. Here are some examples:NotNull<T>
is implicitly cast to and fromT
so you can use it just about anywhere you need it. For example, you can pass aPerson
object to a method that takes aNotNull<Person>
:As you can see above as with nullable you would access the underlying value through the
Value
property. Alternatively, you can use an explicit or implicit cast, you can see an example with the return value below:Or you can even use it when the method just returns
T
(in this casePerson
) by doing a cast. For example, the following code would just like the code above:Combine with Extension
Combine
NotNull<T>
with an extension method and you can cover even more situations. Here is an example of what the extension method can look like:And here is an example of how it could be used:
GitHub
For your reference I made the code above available on GitHub, you can find it at:
https://github.com/luisperezphd/NotNull
Related Language Feature
C# 6.0 introduced the "null-conditional operator" that helps with this a little. With this feature, you can reference nested objects and if any one of them is
null
the whole expression returnsnull
.This reduces the number of null checks you have to do in some cases. The syntax is to put a question mark before each dot. Take the following code for example:
Imagine that
country
is an object of typeCountry
that has a property calledState
and so on. Ifcountry
,State
,County
, orCity
isnull
thenaddress will be
null. Therefore you only have to check whether
addressis
null`.It's a great feature, but it gives you less information. It doesn't make it obvious which of the 4 is null.
Built-in like Nullable?
C# has a nice shorthand for
Nullable<T>
, you can make something nullable by putting a question mark after the type like soint?
.It would be nice if C# had something like the
NotNull<T>
struct above and had a similar shorthand, maybe the exclamation point (!) so that you could write something like:public void WriteName(Person! person)
.On the matter of "what should I do about it", there can be many answers.
A more "formal" way of preventing such error conditions while developing is applying design by contract in your code. This means you need to set class invariants, and/or even function/method preconditions and postconditions on your system, while developing.
In short, class invariants ensure that there will be some constraints in your class that will not get violated in normal use (and therefore, the class will not get in an inconsistent state). Preconditions mean that data given as input to a function/method must follow some constraints set and never violate them, and postconditions mean that a function/method output must follow the set constraints again without ever violating them. Contract conditions should never be violated during execution of a bug-free program, therefore design by contract is checked in practice in debug mode, while being disabled in releases, to maximize the developed system performance.
This way, you can avoid
NullReferenceException
cases that are results of violation of the constraints set. For example, if you use an object propertyX
in a class and later try to invoke one of its methods andX
has a null value, then this will lead toNullReferenceException
:But if you set "property X must never have a null value" as method precondition, then you can prevent the scenario described before:
For this cause, Code Contracts project exists for .NET applications.
Alternatively, design by contract can be applied using assertions.
UPDATE: It is worth mentioning that the term was coined by Bertrand Meyer in connection with his design of the Eiffel programming language.
TL;DR: Try using
Html.Partial
instead ofRenderpage
I was getting
Object reference not set to an instance of an object
when I tried to render a View within a View by sending it a Model, like this:Debugging showed the model was Null inside MyOtherView. Until I changed it to:
And it worked.
Furthermore, the reason I didn't have
Html.Partial
to begin with was because Visual Studio sometimes throws error-looking squiggly lines underHtml.Partial
if it's inside a differently constructedforeach
loop, even though it's not really an error:But I was able to run the application with no problems with this "error". I was able to get rid of the error by changing the structure of the
foreach
loop to look like this:Although I have a feeling it was because Visual Studio was misreading the ampersands and brackets.