The most occurred exception in our development career. Most of us have come across this renowned exception. It is named as NullReferenceException by the Microsoft but what all are the factors that cause it to occur?
NullReferenceException occurs when we try to access a member on type whose value is null. 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 a reference types as Value types are non-nullable.
Being non-nullable, null value can’t be assigned to a value type as value type themselves hold their value on stack. Checkout the following code.
The above code shows how an integer type variable number would not compile because it won’t take a null value. So we will un-assign the null value from the int type number.
Now what’s happening in the above code? I am using a string type variable str and assigning it a null value. This string member will happily accept the null value because it is a reference type. So you will ask why the visual studio didn’t show any error now? This is because reference type variables are stored on stack and this variable will point to a value on heap, where it is stored.
Let’s get back to the above code, I’m assigning number (value type variable) the string member str and converting it to it equivalent type so that it compiles. What you think, it will compile, won’t compile, throw an error?
Yes, it will compile but number won’t be set as null as we know it’s a non-nullable value type. It will be initialized to 0. So NullReferenceException wont occur if we are using Value type members.
Now back to reference types.
As we know Reference type variable are stored on stack and their values are stored on heap. Whenever system tries to access this reference type variable which has no values on heap, it throws an error.
Let’s see an example:
The above code shows simple string which is assigned with a null value. Now here, str is a member on type string which is assigned a value null. I am not assigning any task to this member i.e. it’s not being accessed by us. The output for the above code will just give a blank screen.
But, what if we try to perform a task with this null object (str). Let’s try it.
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.
So who is responsible for this exception?
It’s us, the Developers. NullReferenceException arises due to our fault for not checking the object’s value. We often leave the object values unchecked in the code development.
It also arises when we forget to instantiate our objects. Using methods, properties, collections etc. which can return or set null values can also be the cause of this exception.
How can it be avoided?
There are various ways and methods to avoid this renowned exception:
1. Explicit Checking: We should adhere to the tradition of checking the objects, properties, methods, arrays and collections whether they are null. This can be simply implemented using conditional statements like if-else if-else etc.
2. Exception handling: One of the important ways of managing this exception. Using simple try-catch-finally blocks we can control this exception and also maintain a log of it. This can be very useful when your application is on production stage.
3. Null operators: Null Coalescing operator and null conditional operators can also be used in handy while setting values to objects, variables, properties and fields.
4. Debugger: For developers, we have big weapon of Debugging with us. If have we face NullReferenceException during the development face we can use the debugger to get to the source of the exception.
5. In-built method: System methods such as GetValueOrDefault(),IsNullOrWhiteSpace() and IsNullorEmpty() checks for nulls and assign the default value if there is a null value.
Hope this helps! If you have any issues, suggestions, feedback or concerns do comment below.