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?
Adding a case when the class name for entity used in entity framework is same as class name for a web form code-behind file.
Suppose you have a web form Contact.aspx whose codebehind class is Contact and you have an entity name Contact.
Then following code will throw a NullReferenceException when you call context.SaveChanges()
For the sake of completeness DataContext class
and Contact entity class. Sometimes entity classes are partial classes so that you can extend them in other files too.
The error occurs when both the entity and codebehind class are in same namespace. To fix this, rename the entity class or the codebehind class for Contact.aspx.
Reason I am still not sure about the reason. But whenever any of the entity class will extend System.Web.UI.Page this error occurs.
For discussion have a look at NullReferenceException in DbContext.saveChanges()
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.
Another scenario is when you cast a null object into a value type. For example, the code below:
It 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:
Here,
SelectedDate
is in fact a property - ofDateTime
type - of theCalendar
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 aNullReferenceException
that is quite difficult to spot, because it lies in ASP.NET generated code which compiles fine...Be aware that regardless of the scenario, the cause is always the same in .NET:
Interestingly, none of the answers on this page mention the two edge cases, hope no one minds if I add them:
Edge case #1: concurrent access to a Dictionary
Generic dictionaries in .NET are not thread-safe and they sometimes might throw a
NullReference
or even (more frequent) aKeyNotFoundException
when you try to access a key from two concurrent threads. The exception is quite misleading in this case.Edge case #2: unsafe code
If a
NullReferenceException
is thrown byunsafe
code, you might look at your pointer variables, and check them forIntPtr.Zero
or something. Which is the same thing ("null pointer exception"), but in unsafe code, variables are often cast to value-types/arrays, etc., and you bang your head against the wall, wondering how a value-type can throw this exception.(Another reason for non-using unsafe code unless you need it, by the way)
Literally the easiest way to fix a NullReferenceExeption has two ways. If you have a GameObject for example with a script attached and a variable named rb (rigidbody) this variable will start null when you start your game.
This is why you get a NullReferenceExeption because the computer does not have data stored in that variable.
I'll be using a RigidBody variable as an example.
We can add data really easily actually in a few ways:
Then go into your script and type
rb = GetComponent<Rigidbody>();
This line of code works best under your
Start()
orAwake()
functions.rb = AddComponent<RigidBody>();
Further Notes: If you want unity to add a component to your object and you might have forgotten to add one, you can type
[RequireComponent(typeof(RigidBody))]
above your class declaration (the space below all of your usings).Enjoy and have fun making games!