Passing static parameters to a class

koumides picture koumides · May 4, 2010 · Viewed 18.8k times · Source

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?

Answer

AlfredBr picture AlfredBr · May 4, 2010

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.