-2

Here I have this class which is basically a data structure:

public class Config
{
    public uint? Release { get; set; }
    public string InstallPath { get; set; }
    public uint? CheckEveryXMinutes { get; set; }

    public override string ToString()
    {
        return $"(Release: {Release}, InstallPath: {InstallPath}, CheckEveryXMinutes {CheckEveryXMinutes})";
    }
}

And I want to use this structure as property of another class like this:

public class ConfigRegistry
{
    public Config Result { get; set; }
        
    public ConfigRegistry (string registryKey)
    {
        Result.Release = 0; 
        Console.WriteLine("Read Release from registry: {0}", Result.Release);
    }
}

And I'm getting an error at "Result.Release = 0" line:

Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.

What am I doing wrong here?

user2838376
  • 149
  • 2
  • 11

1 Answers1

2

I needed to add

Result = new Config();
user2838376
  • 149
  • 2
  • 11
  • Indeed. Two improvement suggestions: (1) You can initialize the class right at the property declaration: `public Config Result { get; set; } = new Config();`. (2) You can remove the public setter: This will only allow users to change individual properties in your Result object, rather than replacing the complete Result instance itself: `public Config Result { get; } = new Config();`. – Heinzi Jan 04 '23 at 11:57