Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")     } } 
like image 708
MrProgram Avatar asked Dec 11 '15 08:12

MrProgram


People also ask

Can we pass parameters to static constructor?

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.

Can static constructors use optional arguments?

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.

Why static constructor is Parameterless in C#?

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.


1 Answers

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.

like image 90
Matías Fidemraizer Avatar answered Oct 01 '22 09:10

Matías Fidemraizer