Earn income with your C# skills
Sign up and we'll send you the best freelance opportunities straight to your inbox.
We're building the largest self-service freelancing marketplace for people like you.

What is a NullReferenceException, and how to fix it.

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");
    }
}



Stay Inspired!
Join other developers and designers who have already signed up for our mailing list.
Terms     Privacy     Licensing       EULA       Sitemap      
© Data & Object Factory, LLC.
Made with    in Austin, Texas.      Vsn 1.3.0