On numerous occasions, a , is received NullReferenceException
, being one of the exceptions that raises the most questions. What does it mean NullReferenceException
and how can it be fixed?
For the NullReferenceException
in VB.NET, see NullReferenceException: What is it and how can I fix it?
What is the cause?
Essentially
You are trying to use some object that is
null
(orNothing
in VB.NET). This means that either you have initialized it tonull
, or you never initialized it.null
is a value like the others, and is passed in the same way. If you havenull
in method "A", it may be that method "B" has passed anull
to method "A".The rest of this answer is going to go into more detail and show common mistakes many programmers make that can lead to a
NullReferenceException
.More specifically
When the runtime launches one
NullReferenceException
it always means the same thing: you are trying to use a reference. This reference has not been initialized (or was initialized at some point , but is no longer initialized).This means that the reference is
null
, and members of a reference cannot be accessed if the reference isnull
. This is the simplest case:This code will throw one
NullReferenceException
on the second line, since the instance method cannot be calledToUpper()
on a reference ofstring
pointing tonull
.Depuration
How do I find the source of an exception
NullReferenceException
? In addition to studying the exception itself, which will be thrown in the exact place where it occurs, the general debugging rules in Visual Studio should be applied: set breakpoints strategically and inspect the variables , either by placing the cursor mouse over their names, by opening a (Quick) Watch window, or by using existing debugging panels such as Locals and Auto.If you want to find where the reference is or is not assigned, right-click on its name and choose "Find all references". You can then put a breakpoint on all found locations and run the program again in debug. Every time the debugger stops execution at that point, you'll need to determine if you expected the reference at that point to be non-null, by inspecting the variable and verifying that it points to an instance when it should.
By following the flow of the program in this way, you will be able to find the location where the instance should not be null, and why it has not been initialized as it should.
examples
Some common scenarios where we can encounter this exception:
generic
If ref1 or ref2 or ref3 is
null
, then you will get aNullReferenceException
. If you want to solve this problem, then you need to find which one it is bynull
rewriting the expression to its simplest equivalent:For example, in
HttpContext.Current.User.Identity.Name
, theHttpContext.Current
could benull
, or the propertyUser
could benull
, or the propertyIdentity
could benull
.class instances
When any reference type (class) variable is created, by default it is initialized to
null
.Class variables must either be initialized or assigned with an instance of the same class already initialized. Initialization is achieved using the keyword
new
.Hint
If you want to avoid the null reference of the child (Person), you could initialize it in the constructor of the parent (Book).
The same applies to nested object initializers:
Although the keyword is used in this example
new
, it only creates a new instance ofLibro
, not a new instance ofPersona
, so the propertyAutor
remainsnull
.Arrays
Elements of an Array
Irregular Arrays ( Jagged Arrays )
Collections/Lists/Dictionaries
Range variables (Indirect/Deferred)
events
Names that do not follow the conventions:
If you had named the fields differently than the local variables, you might have noticed that you never initialized the field.
This can be worked around by following the convention that fields have an underscore (
_
) added before the name:Life cycle of an ASP.NET page:
ASP.NET Session Values
ASP.NET MVC Empty View Models
If the exception occurs when a property is referenced
@Modelo
in an ASP.NET MVC view, you need to understand that theModelo
is initialized in your methodaction
, when you return(return
) a view. When you return an empty model (or a model property) from your controller, the exception is thrown when the view accesses it:Creation order of controls and events in WPF
WPF controls are created during the call to
InitializeComponent
in the order they appear in the visual tree. An exceptionNullReferenceException
can be thrown if controls created earlier with event handlers, etc. , which fire duringInitializeComponent
, reference controls created after.For example:
Here
comboBox1
it is created beforelabel1
. If the eventcomboBox1_SelectionChanged
tries to referencelabel1
, it has not yet been created.Changing the order of the declarations in the XAML (for example, putting
label1
beforecomboBox1
, ignoring design philosophy issues), would at least solve theNullReferenceException
in this case.cast with
as
This would not throw an InvalidCastException, but would return
null
when the cast fails (and whenunObjeto
null). So you have to be careful with it.LINQ FirstOrDefault() and SingleOrDefault()
The simple versions
First()
andSingle()
throw an exception when there is nothing. Versions"OrDefault"
return null in that case. You must be aware of it.foreach
foreach
throws an exception when you try to iterate over a null collection. This is usually caused by an unexpected null result from a method that returns a collection.A more realistic example - selecting nodes from an XML document. The exception will be thrown if the nodes are not found but an initial debug shows that all properties are valid:
ways to avoid it
Explicitly check
null
for and ignore null values.If you anticipate that the reference might ever be null, you can ask if it is
null
before accessing the members of the instance:Explicitly check
null
and return a default value.Calls to methods that you expect to return an instance might return
null
, for example when the object being searched for is not found. You can choose to return a default value in these cases:Explicitly check
null
and throw a custom exception.You could also throw a custom exception, so you can catch it in the code that calls the method:
Use
Debug.Assert
if a value should never benull
, to catch the problem before the exception is thrown.When you know in the development stage that a method might return
null
even though this should never happen, you can useDebug.Assert()
to stop the program flow as soon as possible when it happens:This check will not be performed on your Release Build , causing it to
NullReferenceException
be released againlibro == null
at runtime.Use
GetValueOrDefault()
in "Nullable" value types ( nullables ) to get a default value when they are null.Use the null coalescing operator :
??
[C#] orIf()
[VB].The shortest way to provide a default value when null is encountered:
Use the null condition operator:
?.
(available in C# 6 and VB.NET 14):This operator is also called safe navigation or Elvis (because of its shape). If the expression on the left side of the operator is
null
, the right side of the operator is not evaluated, and , is returned insteadnull
. In this case:If the person doesn't have a title, this code will throw an exception because it's trying to call
ToUpper
on a property with a null value.In C# 5 and below, this can be fixed like so:
Now the variable
titulo
will benull
instead of throwing an exception. C# 6 introduces a shorter syntax that does the same thing:The result of this is that the variable
titulo
will be assigned null, and the call toToUpper
will never be made if itpersona.Titulo
isnull
.Of course, you still have to check that
title
it is notnull
or use the null condition operator in conjunction with the null check operator (??
) to provide a default value:This answer is a translation of the great answer found on the English version of Stack Overflow
In my case I had a List initialized to null
I changed the initialization for the object type and it was solved