I have a static XDocument property and I am having trouble setting it to a value.
The code involved would be like this:
public static class ProjectXmlEngine
{
public static XDocument ProjectsDataFile { get; set; }
}
And in my program class I set it like that:
static class Program
{
AppConfig.Initialize();
ProjectXmlEngine.ProjectsDataFile = XDocument.Load(AppConfig.ProjectsDataFile);
}
I am getting an error with Inner Exception: "Object reference not set to an instance of an object."
Properties somewhere else in my application did not throw this exception but they where string, int, bool, does it have something to do with this property being an object ?
EDIT
public static class AppConfig
{
private static string projectsDataFile;
static AppConfig()
{
ProjectsDataFile = ConfigurationManager.AppSettings["ProjectsDataFile"];
}
public static string ProjectsDataFile
{
get { return projectsDataFile; }
set { projectsDataFile = ConvertTokenToValue(value); }
}
public static void Initialize()
{
}
}
This class don't have the same error as the ProjectXmlEngine
EDIT 2 (Solution)
I found what was causing the error.
The class ProjectXmlEngine
contains other lines of codes I didn't mention because I thought it irrelevant to the problem.
The class contained some field variables that was dependent on my property:
public static class ProjectXmlEngine
{
public static XNamespace Namespace = ProjectsDataFile.Root.GetDefaultNamespace();
// In the above line the 'ProjectsDataFile' property is null when this field's value is set
public static XName TagProject = Namespace + "project";
public static XName TagProjCode = Namespace + "wpcode";
public static XName TagProjName = Namespace + "wpname";
}
I solved this by adding a static constructor and set the values of the fields in this constructor.
public static class ProjectXmlEngine
{
private static XDocument projectsDataFile;
public static XNamespace Namespace;
public static XName TagProject;
public static XName TagProjCode;
public static XName TagProjName;
static ProjectXmlEngine()
{
ProjectsDataFile = XDocument.Load(AppConfig.ProjectsDataFile);
Namespace = ProjectsDataFile.Root.GetDefaultNamespace();
TagProject = Namespace + "project";
TagProjCode = Namespace + "wpcode";
TagProjName = Namespace + "wpname";
}
public static XDocument ProjectsDataFile { get; set; }
}