Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 738
koumides Avatar asked May 04 '10 16:05

koumides


People also ask

Can we pass static class as parameter C#?

C# Static types cannot be used as parameters.

What will happen if we pass parameters to static constructor?

A static constructor is called automatically to initialize the class before the first instance is created, so we can't send it any parameters. You cant pass parameters to Static Constructors, because you cannot access any non-static member outside of a static method (constructor too).

Can a class be static?

Classes can be static which most developers are aware of, henceforth some classes can be made static in Java. Java supports Static Instance Variables, Static Methods, Static Block, and Static Classes. The class in which the nested class is defined is known as the Outer Class.

When would you use a static class?

Static classes are used as containers for static members. Static methods and static properties are the most-used members of a static class. All static members are called directly using the class name. Static methods do a specific job and are called directly using a type name, rather than the instance of a type.


1 Answers

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.

like image 132
AlfredBr Avatar answered Oct 11 '22 05:10

AlfredBr