Dofactory.com
Dofactory.com

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


Jack Poorte
Jack Poorte
Last updated on Sep 30, 2023



Stay Inspired!
Join other developers and designers who have already signed up for our mailing list.
Terms     Privacy     Cookies       Do Not Sell       Licensing      
Made with    in Austin, Texas.  - vsn 44.0.0
© Data & Object Factory, LLC.