I have a static class:
public static class Options
{
public static MiscSettings MiscSettings;
public static Units Units;
}
My definitions for the two property classes looks like this:
[Serializable]
public class Units
{
public LengthUnit LengthUnit { get; set; } = LengthUnit.Millimeter;
public VolumeUnit VolumeUnit { get; set; } = VolumeUnit.CubicCentimeter;
}
[Serializable]
public class MiscSettings
{
public bool OutputDebugging { get; set; } = false;
}
When I do:
Options.Units = OptionsData.Units;
Options.MiscSettings.OutputDebugging = false;
The first line executes ok. The second gives me a NullReference Exception. The property Options.MiscSettings is null. The next error is Object not set to an instance of an object.
I've tried renaming everything, changing order of the properties. I also tried moving the property OutputDebugging to the Units class and that worked just fine.
Any help would be appreciated.
CodePudding user response:
Just because a field is static doesn't mean you don't have to initialize it. Here, MiscSettings
is never initialized, so it's null
, and when you try to set its OutputDebugging
you get the aforementioned NullReferenceException
.
One easy way to to set OutputDebuggin
would be to initialize MiscSettings
with an object initializer:
Options.MiscSettings = new MiscSettings
{
OutputDebugging = false;
}
CodePudding user response:
try this
if(Options.MiscSettings==null) Options.MiscSettings=new MiscSettings();
Options.MiscSettings.OutputDebugging = false;
CodePudding user response:
When you are creating a class object, you need to make sure to initialize the variables you will use. The MiscSettings variable is not set, therefore you are getting a NullReferenceException.Options.MiscSettings = new MiscSettings();