A NullReferenceException
occurs when you try to access an object/method/variable which has no value or technically has a value of null
, for example:
using System;
using System.Collections.Generic;
public class Example
{
public static void Main(string[] args)
{
int value = Int32.Parse(args[0]);
List<String> names;
if (value > 0)
names = new List<String>();
names.Add("Major Major Major");
}
}
source: https://msdn.microsoft.com/en-us/library/system.nullreferenceexception(v=vs.110).aspx
In the code above. The program will create a list of strings called names
and then on an IF-statement it will instantiate the list of names, and since the only way the list will be instantiated is IF a CONDITIONAL statement succeeds and conditional statements are commonly known to not always be true.
So therefore the code will be like this, A list of strings called names is created and equals null
(because the programmer did not equal it to anything like this; List<string> names;
instead of this;
List<string> names = new List<string>();
The code above, I gave you can also cause a NullPointerException
(If the if-statement and the code inside it, is removed).
So to fix that we would need to remove the If statement altogether and instantiate the list of names, so the code will now look like this.
using System;
using System.Collections.Generic;
public class Example
{
public static void Main(string[] args)
{
int value = Int32.Parse(args[0]);
List<String> names = new List<String>();
names.Add("Major Major Major");
}
}
Another example:
string i;
if(i == "hello") {/*Do something*/}
// Causes error because I is not set to any value or null
// (null is mostly the default variable given to any object/method/variable that is not specified to contain any value specified by the programmer)
Fix:
string i;
i = "hi";
if(i == "hello") {/*Do something*/}
// Will not throw exception but returns false because I is set to hi and not hello
//Or you could just do this int i = 1; and remove the "i = 1" part
P.S: I hope you haven't figured this out before I answered your question, otherwise my effort to explain and answer your question would've been useless.