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") } }
A static constructor doesn't take access modifiers or have parameters. A class or struct can only have one static constructor. Static constructors cannot be inherited or overloaded.
Static constructors can use optional arguments. Overloaded constructors cannot use optional arguments. If we do not provide a constructor, then the compiler provides a zero-argument constructor.
When a data member is shared among different instances it is imperative that data should be consistent among all the instances of the class. And also there is no way to call static constructor explicitly. Therefore the purpose of having a parameterized static constructor is useless.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With