Reputation: 1713
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>[email protected]</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);
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;
}
Upvotes: 0
Views: 713
Reputation: 1713
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.
Upvotes: 1