Search code examples
c#staticsingleton

How to implement this using static / singleton design pattern?


I want to implement a configuration helper.

The usage will be something like this:

var companyName = ConfigHelper.Company.Name;
var redirectURL = ConfigHelper.URLs.DefaultRedirectURL; 

As you can see in the above examples, I have ConfigHelper which should not require an instance, however it will consist of sub classes (Company and URLs), and here I want access to the properties (not methods).

I want this all done without any class instances required, and not sure if I should be using static / singleton.

E.g. will ConfigHelper be defined as static? Will the sub classes be defined as regular classes and will they become static properties of ConfigHelper?


Solution

  • Yes you're on the right track, ConfigHelper will be a static class and the properties will just be regular classes, but those will be instances.

    For example:

    public class Company
    {
    
        public string Name { get; set; }
    
    }
    
    public static class ConfigHelper
    {
    
        static ConfigHelper()
        {
            Company = new Company();
        }
    
        public static Company Company { get; private set; }
    
    }