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?
Simon Mourier gave this example:
where an unboxing conversion (cast) from
object
(or from one of the classesSystem.ValueType
orSystem.Enum
, or from an interface type) to a value type (other thanNullable<>
) in itself gives theNullReferenceException
.In the other direction, a boxing conversion from a
Nullable<>
which hasHasValue
equal tofalse
to a reference type, can give anull
reference which can then later lead to aNullReferenceException
. The classic example is:Sometimes the boxing happens in another way. For example with this non-generic extension method:
the following code will be problematic:
These cases arise because of the special rules the runtime uses when boxing
Nullable<>
instances.You can fix NullReferenceException in a clean way using Null-conditional Operators in c#6 and write less code to handle null checks.
It's used to test for null before performing a member access (?.) or index (?[) operation.
Example
is equivalent to:
The result is that the name will be null when p is null or when p.Spouse is null.
Otherwise, the variable name will be assigned the value of the p.Spouse.FirstName.
For More details : Null-conditional Operators
It means your code used an object reference variable that was set to null (i.e. it did not reference an actual object instance).
To prevent the error, objects that could be null should be tested for null before being used.
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)
.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.
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.