C # instance constructor and Static Constructor

What is the difference between the two? I used only one type of constructor, and I consider it a static constructor. Only familiarity with C ++ and Java.

+6
constructor c # static-constructor
source share
3 answers

The static constructor is called first when your class is referenced, i.e.

MyClass.SomeStaticMethod() 

The instance constructor is called every time you do " MyClass dummy = new MyClass() ", i.e. create an instance of the class

It is semantically first used when you want some static state to be initialized before it is accessed, another is used to initialize instance members.

+11
source share

Static constructors allow you to initialize static variables in a class or do other things that need to be done in a class after they first reference your code. They are called only once every time your program starts.

Static constructors are declared with this syntax and cannot be overloaded or have any parameters, because they start when your class refers to its name:

 static MyClass() { } 

Instance constructors are those that are called whenever you create new objects (class instances). They are also the ones you usually use in Java and most other object-oriented languages.

You use them to give your new objects their initial state. They can be overloaded and can take parameters:

 public MyClass(int someNumber) : this(someNumber, 0) {} public MyClass(int someNumber, int someOtherNumber) { this.someNumber = someNumber; this.someOtherNumber = someOtherNumber; } 

Call Code:

 MyClass myObject = new MyClass(100, 5); 
+5
source share

The static constructor runs only once for all instances or use of the class. It will be launched the first time you use the class. Regular constructors are started when the class object is created.

Everything you need to know about static constructors can be found here: http://msdn.microsoft.com/en-us/library/k9x6w0hc(v=VS.100).aspx

+1
source share

All Articles