DEV Community

Francesco Girelli
Francesco Girelli

Posted on

C# Constants Management

Hi devs!
I'm a 22 yo dev and some days ago I looked out for the best practices to store and manage constants in a project. I found a guy on StackOverflow that said that you must create a static class with static methods that return the constant value, in that way you have all the constants inside one file and if you ever have to make a change you can easily find the constant... but I was thinking "If I want to be able to switch to debug constants or release constants without writing too much checks inside my code and have a strong consistency, how can I make it based on this 'best practice'?" so I wrote this, it works but i wanted to know from more expert dotnet and C# devs if it is a good way to do that or not:

public abstract class ConstantsBase 
{
    public static ConstantsBase Instance {get; set;}
    protected ConstantsBase() {}

    public abstract string GetSomeValue();
}

public class ConstantsA : ConstantsBase
{
    public override string GetSomeValue()
    {
        return "SomeValue";
    }
}

public class ConstantsB : ConstantsBase
{
    public override string GetSomeValue()
    {
        return "SomeOtherValue";
    }
}

public class Program 
{
    public static void Main()
    {
        #if DEBUG
        ConstantsBase.Instance = new ConstantsA();
        #elif RELEASE
        ConstantsBase.Instance = new ConstantsB();
        #endif

        Console.WriteLine(ConstantsBase.Instance.GetSomeValue());
    }
}
Enter fullscreen mode Exit fullscreen mode

I designed it as a singleton so it can be called from anywhere inside the program without being instantiated.

Top comments (0)