简体   繁体   中英

NullReferenceException with static class property

I have a static class that looks like this:

namespace Argus
{
    static class Argus
    {
        public static List<Branch> myArgus;
    }
}

and elsewhere in my code I have this:

// Add this branch to myArgus
Argus.myArgus.Add(branch);

When I run the code, I get this error:

Object reference not set to an instance of an object.

I have verified that branch is valid (it's an object of the Branch class), and have no idea what could be wrong here. I'm trying to read branch data in from a text file.

You need to instantiate it; it's default value is null otherwise:

public static List<Branch> myArgus = new List<Branch>();

您必须实例化myArgus

public static List<Branch> myArgus = new List<Branch>();

You are never allocating memory for myArgus . Of course it's null .

public static List<Branch> myArgus = new List<Branch>();

You must always make references point to allocated objects in memory, otherwise they cannot be used. Trying to invoke operations on references not pointing to allocated memory will result in NullPointerException .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM