简体   繁体   中英

C# NullReferenceException but nothing is null

I have a C# class with a field and a property that looks like this.

public static class Config {
    // ...
    private static string admin_email;
    public static string AdminEmail {
        get {
            if (admin_email == null) {
                admin_email = config_xml.Element("admin_email").Value;
            //  ^ The exception is thrown here.
            }
            return admin_email;
        }
    }
}

In the above code, config_xml is an XElement which contains a child element that looks like

<admin_email>myemail@example.com</admin_email>

However, when I try to access this property, I get a NullReferenceException even though the debugger shows that nothing is null.

I checked the debugger, and watching config_xml.Element("admin_email").Value shows the email, as expected.

The weird part is that when I put a breakpoint on that line and step in one step at a time there is no exception thrown.

I have tried with and without enabling the option Just My Code.

In case this helps, I try to access the property on a line like this (from a different project)

message.From = new MailAddress(Config.AdminEmail);

Edit

After changing the code to this, I realised that c was still null.

get {
    if (admin_email == null) {
        XElement c = config_xml;
        XElement e = c.Element("admin_email");
    //  ^ Exception is now thrown here
        string v = e.Value;
        admin_email = v;
    }
    return admin_email;
}

Thank you David, asawyer, and Lasse V. Karlsen for helping me realise my mistake. I changed my code to this, and now it works.

admin_email = new Email(ConfigXml.Element("admin_email").Value;

I was using a similar technique for config_xml and ConfigXml , so I would only load the XML into the field config_xml if it was ever needed, and I forgot to access it with the property ConfigXml (which did the loading) instead of the field config_xml (which was null until I used the property).

I don't know why it was working with a breakpoint, maybe when I watched the property it assigned it? I don't know.

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