What Is a Nullreferenceexception, and How Do I Fix It?
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...
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?
27 Answers
What is the cause?
Must Read
Bottom Line
You are trying to use something that is null (or Nothing in VB.NET). This means you either set it to null, or you never set it to anything at all.
Like anything else, null gets passed around. If it is null in method "A", it could be that method "B" passed a null to method "A".
null can have different meanings:
- Object variables that are uninitialized and hence point to nothing. In this case, if you access members of such objects, it causes a
NullReferenceException. - The developer is using
nullintentionally to indicate there is no meaningful value available. Note that C# has the concept of nullable datatypes for variables (like database tables can have nullable fields) - you can assignnullto them to indicate there is no value stored in it, for exampleint? a = null;(which is a shortcut forNullable<int> a = null;) where the question mark indicates it is allowed to storenullin variablea. You can check that either withif (a.HasValue) {...}or withif (a==null) {...}. Nullable variables, likeathis example, allow to access the value viaa.Valueexplicitly, or just as normal viaa.
Note that accessing it viaa.Valuethrows anInvalidOperationExceptioninstead of aNullReferenceExceptionifaisnull- you should do the check beforehand, i.e. if you have another non-nullable variableint b;then you should do assignments likeif (a.HasValue) { b = a.Value; }or shorterif (a != null) { b = a; }.
The rest of this article goes into more detail and shows mistakes that many programmers often make which can lead to a NullReferenceException.