Search code examples
c#classstaticstatic-classesstatic-constructor

How to pass parameter to static class constructor?


I have a static class with a static constructor. I need to pass a parameter somehow to this static class but I'm not sure how the best way is. What would you recommend?

public static class MyClass {

    static MyClass() {
        DoStuff("HardCodedParameter")
    }
}

Solution

  • Don't use a static constructor, but a static initialization method:

    public class A
    {
        private static string ParamA { get; set; }
    
        public static void Init(string paramA)
        {
            ParamA = paramA;
        }
    }
    

    In C#, static constructors are parameterless, and there're few approaches to overcome this limitation. One is what I've suggested you above.