Search code examples
c#static-membersstatic-constructor

Passing static parameters to a class


As far as I know you can can't pass parameters to a static constructor in C#. However I do have 2 parameters I need to pass and assign them to static fields before I create an instance of a class. How do I go about it?


Solution

  • This may be a call for ... a Factory Method!

    class Foo 
    { 
      private int bar; 
      private static Foo _foo;
    
      private Foo() {}
    
      static Foo Create(int initialBar) 
      { 
        _foo = new Foo();
        _foo.bar = initialBar; 
        return _foo;
      } 
    
      private int quux; 
      public void Fn1() {} 
    } 
    

    You may want to put a check that 'bar' is already initialized (or not) as appropriate.