A NullReferenceException exception is thrown when the code tries to access a member on a type whose value is null.
Example: You've forgotten to instantiate a reference type.
In the following example, names
is declared, but,
depending on the incoming args, it is never instantiated:
using System;
using System.Collections.Generic;
public class Example
{
public static void Main(string[] args)
{
int value = int.Parse(args[0]);
List<string> names;
if (value > 0)
names = new List<string>();
// Potential null reference exception
names.Add("Leslie Cariolli");
}
}
To address this problem, instantiate the object so that its value is no longer null. The following example does this by always calling the type's class constructor.
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
var names = new List<string>();
names.Add("Leslie Cariolli");
}
}