I have some code and when it executes, it throws a
Object reference not set to an instance of an object.
What does this mean, and what can I do to fix this error?
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.
It means that the variable in question is pointed at nothing. I could generate this like so:
That will throw the error because while I've declared the variable "
To avoid this error:
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.
What is the cause?
You are trying to use something that is
Like anything else,
The rest of this article goes into more detail and shows mistakes that many programmers often make which can lead to a
The runtime throwing a
This means the reference is
This will throw a
How do you find the source of a
If you want to find out where the reference is or isn't set, right-click its name and select "Find All References". You can then place a breakpoint at every found location and run your program with the debugger attached. Every time the debugger breaks on such a breakpoint, you need to determine whether you expect the reference to be non-null, inspect the variable and and verify that it points to an instance when you expect it to.
By following the program flow this way, you can find the location where the instance should not be null, and why it isn't properly set.
Some common scenarios where the exception can be thrown:
If ref1 or ref2 or ref3 is null, then you'll get a
When creating a variable of a reference (class) type, it is by default set to
Class type variables must either be initialized or set to an already existing class instance. Initialization is done by using the
If you want to avoid the child (Person) null reference, you could initialize it in the parent (Book) object's constructor.
Nested Object Initializers
The same applies to nested object initializers:
This translates to
Nested Collection Initializers
The nested collection initializers behave the same:
This translates to
Range Variable (Indirect/Deferred)
Bad Naming Conventions:
If you named fields differently from locals, you might have realized that you never initialized the field.
This can be solved by following the convention to prefix fields with an underscore:
ASP.NET Page Life cycle:
ASP.NET Session Values
ASP.NET MVC empty view models
If the exception occurs when referencing a property of
WPF Control Creation Order and Events
WPF controls are created during the call to
For example :
Changing the order of the declarations in the XAML (i.e., listing
Be aware that regardless of the scenario, the cause is always the same in .NET:
An example of this exception being thrown is: When you are trying to check something, that is null.
The .NET runtime will throw a NullReferenceException when you attempt to perform an action on something which hasn't been instantiated i.e. the code above.
In comparison to an ArgumentNullException which is typically thrown as a defensive measure if a method expects that what is being passed to it is not null.
More information is in C# NullReferenceException and Null Parameter.
Another scenario is when you cast a null object into a value type. For example, the code below:
It will throw a
One example of this is this simple ASP.NET binding fragment with the Calendar control:
You are using the object that contains the null value reference. So it's giving a null exception. In the example the string value is null and when checking its length, the exception occurred.
The exception error is:
Another case where
In general, you should use a cast or
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:
If you are unsure of the type, but you want to try to use it as a specific type, then use
If you have not initialized a reference type, and you want to set or read one of its properties, it will throw a NullReferenceException.
You can simply avoid this by checking if the variable is not null:
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):
Value types (you can simply ignore these ones):
Another general case where one might receive this exception involves mocking classes during unit testing. Regardless of the mocking framework being used, you must ensure that all appropriate levels of the class hierarchy are properly mocked. In particular, all properties of
See "NullReferenceException thrown when testing custom AuthorizationAttribute" for a somewhat verbose example.
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()
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
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.
in the following line the only code that can cause the exception is if
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
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.
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.
where an unboxing conversion (cast) from
In the other direction, a boxing conversion from a
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
NullReference Exception — Visual Basic
This answer will use Visual Basic terms, syntax, and context. The examples used come from a large number of past Stack Overflow questions. This is to maximize relevance by using the kinds of situations often seen in posts. A bit more explanation is also provided for those who might need it. An example similar to yours is very likely listed here.
The message "Object not set to an instance of Object" means you are trying to use an object which has not been initialized. This boils down to one of these:
Finding The Cause
Since the problem is an object reference which is
You should also remove any Try/Catch blocks from the relevant code, especially ones where there is nothing in the Catch block. This will cause your code to crash when it tries to use an object which is
You can also use the
Once you know what and where the problem is, it is usually fairly easy to fix and faster than posting a new question.
Examples and Remedies
Class Objects / Creating an Instance
The problem is that
When it is only appropriate to create the instance later:
Note: Do not use
This will create a local variable,
To be clear,
For more information, see:
Arrays must also be instantiated:
This array has only been declared, not created. There are several ways to initialize an array:
Note: Beginning with VS 2010, when initializing a local array using a literal and
The data Type and array size are inferred from the data being assigned. Class/Module level declarations still require
Example: Array of class objects
The array has been created, but the
For more information, see:
Lists and Collections
.NET collections (of which there are many varieties - Lists, Dictionary, etc.) must also be instantiated or created.
You get the same exception for the same reason -
A common oversight is a class which uses a collection
Either procedure will result in an NRE, because
As before, this is incorrect:
For more information, see
Data Provider Objects
Working with databases presents many opportunities for a NullReference because there can be many objects (
As before, the
When declared as a module/class level variable, as appears to be the case with
A typo is a problem here:
Since this uses one table, using
The Remedy is the same, reference the table by index:
See also DataTable Class.
Object Paths / Nested
The code is only testing
It is not possible to reference anything 'downstream' of a
Among other things, this code does not anticipate that the user may not have selected something in one or more UI controls.
Validate data before using it (also use
Alternatively, you can use
Visual Basic Forms
This is a fairly common way to get an NRE. In C#, depending on how it is coded, the IDE will report that
The arrays and collections cannot be initialized this way. This initialization code will run before the constructor creates the
Referencing array elements later will result in an NRE. If you do this in
Since no other code in your
Note this applies to any and all control and component references making these illegal where they are:
It is curious that VB does not provide a warning, but the remedy is to declare the containers at the form level, but initialize them in form load event handler when the controls do exist. This can be done in
The array code may not be out of the woods yet. Any controls which are in a container control (like a
These should be easy to find now that you know what you are looking for:
"Button2" resides on a
Rather than indirect references by name using the form's
Function Returning Nothing
This is a case where the IDE will warn you that 'not all paths return a value and a
Poorly Implemented Try/Catch
A badly implemented Try/Catch can hide where the problem is and result in new ones:
This is a case of an object not being created as expected, but also demonstrates the counter usefulness of an empty
There is an extra comma in the SQL (after 'mailaddress') which results in an exception at
Don't use empty Try/Catch blocks - let the code crash so you can a) identify the cause b) identify the location and c) apply a proper remedy. Try/Catch blocks are not intended to hide exceptions from the person uniquely qualified to fix them - the developer.
DBNull is not the same as Nothing
As before, you can test for Nothing, then for a specific value:
The DGV has a few quirks seen periodically:
Name the columns manually, or reference by index:
Example 2 — Beware of the NewRow
If you do use a
Under certain circumstances, trying to use an item from
Since VB is managing Settings for you, it is reasonable to expect it to initialize the collection. It will, but only if you have previously added an initial entry to the collection (in the Settings editor). Since the collection is (apparently) initialized when an item is added, it remains
Initialize the settings collection in the form's
You probably forgot the
Something you assumed would perform flawlessly to return an initialized object to your code, did not.
Don't ignore compiler warnings (ever) and use
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
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
I was getting
Debugging showed the model was Null inside MyOtherView. Until I changed it to:
And it worked.
Furthermore, the reason I didn't have
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
Although I have a feeling it was because Visual Studio was misreading the ampersands and brackets.
Well, in simple terms:
You are trying to access an object that isn't created or currently not in memory.
So how to tackle this:
By finding by name I mean some framework allow you to FIndObjects using strings and the code might look like this: FindObject("ObjectName");
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.
For example, methods can check the different arguments to see if they are null and throw an
The constructor for the
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
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
Plain 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
You would use very similar to the same way you would use
As you can see above as with nullable you would access the underlying value through the
Or you can even use it when the method just returns
Combine with Extension
And here is an example of how it could be used:
For your reference I made the code above available on GitHub, you can find it at:
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
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:
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
It would be nice if C# had something like the
NullReferenceException or Object reference not set to an instance of an object occurs when an object of the class you are trying to use is not instantiated. For example:
Assume that you have a class named Student.
Now, consider another class where you are trying to retrieve the student's full name.
As seen in the above code, the statement Student s - only declares the variable of type Student, note that the Student class is not instantiated at this point. Hence, when the statement s.GetFullName() gets executed, it will throw the NullReferenceException.
The error line "Object reference not set to an instance of an object. " states that you have not assigned instance object to a object reference and still you are accessing properies/methods of that object.
for example: let say you have a class called myClass and it contains one property prop1.
Now you are accessing this prop1 in some other class just like below:
above line throws error because reference of class myClass is declared but not instantiated or an instance of object is not assigned to referecne of that class.
To fix this you have to instantiate (assign object to reference of that class).
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
Edge case #2: unsafe code
(Another reason for non-using unsafe code unless you need it, by the way)
It means you are trying to manipulate something which has reference but not yet initialized
There is a scenario that can happen that is Class related. The question ended up getting closed prior to my stating the resolution: //allinonescript.com/questions/43348009/unable-to-instantiate-class
Beware of classes not instantiating: If any part of your constructor in a class throws a
I instantiated a class:
Inside the class itself was a call to get a connection string from the
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
When I get this error, I add the following code to any event handler that triggers the error.
The ! means "not", FYI. So if the object in question isn't loaded, the program terminates the execution and prevents the crash.
This is basically is a Null reference exception. As Microsoft states-
What does that mean?
That means if any member which doesn’t hold any value and we are making that member to perform certain task then the system will undoubtedly toss a message and say-
“Hey wait, that member has no values so it can’t perform the task which you are handing it over.”
The exception itself says that something is being referred but whose value is not being set. So this denotes that it only occurs while using reference types as Value types are non-nullable.
NullReferenceException won't occur if we are using Value type members.
The above code shows simple string which is assigned with a null value.
Now, when I try to print the length of the string str, I do get An unhandled exception of type ‘System.NullReferenceException’ occurred message because member str is pointing to null and there can’t be any length of null.
‘NullReferenceException’ also occurs when we forget to instantiate a reference type.
Suppose I have a class and member method in it. I have not instantiated my class but only named my class. Now if I try to use the method, the compiler will throw an error or issue a warning (depending on the compiler).
Compiler for the above code raises an error that variable obj is unassigned which signifies that our variable has null values or nothing. Compiler for the above code raises an error that variable obj is unassigned which signifies that our variable has null values or nothing.
Why it occurs?
How can it be avoided?
There are various ways and methods to avoid this renowned exception:
There are many good answers already here. You can also check more detailed description with examples on my blog.
Hope this helps too!
If we consider common scenarios where this exception can be thrown, accessing properties withing object at the top.
in here , if address is null , then you will get NullReferenceException.
So, as a practice we should always use null check, before accessing properties in such objects (specially in generic)
If one is getting this message during saving or compiling the build, just close all the files and then open any file to compile and save.
For me the reason was that I had rename the file and old file was still open.
To use methods and member of an object you first have to create that object. If you didn't create it (variable that should hold the object is not initialized), but you try to use it's methods or variables you'll get that error.
Sometime you may just forgot to do initialization.
Edited: new can't return null, but fire's exception when failed. Long time ago it was the case in some languages, but not any more. Thanks @John Saunders for pointing that out.
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.
I'll be using a RigidBody variable as an example.
Further Notes: If you want unity to add a component to your object and you might have forgotten to add one, you can type
Reference types default to null to indicate that they are not referencing any object. Hence, if you try and access the object that is being referenced and there isn't one, you will get a NullReferenceException.
When you run this code, you will get :
You can avoid this error by coding like this:
Note: In order to avoid this error you should always initialize your objects before you try to do anything with them.
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.
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