RoR
RoR

Reputation: 16502

C# Instance Constructor vs Static Constructor

What are the differences between the two? I've only used one kind of constructor and I believe it's the static constructor. Only familiar with C++ and Java.

Upvotes: 6

Views: 9543

Answers (3)

Steven Oxley
Steven Oxley

Reputation: 6724

The static constructor runs only once for all instances or uses of the class. It will run the first time you use the class. Normal constructors run when you instantiate an object of the class.

Everything you should need to know about static constructors can be found here: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors

Upvotes: 2

BoltClock
BoltClock

Reputation: 724552

Static constructors allow you to initialize static variables in a class, or do other things needed to do in a class after it's first referenced in your code. They are called only once each time your program runs.

Static constructors are declared with this syntax, and can't be overloaded or have any parameters because they run when your class is referenced by its name:

static MyClass()
{
}

Instance constructors are the ones that are called whenever you create new objects (instances of classes). They're also the ones you normally use in Java and most other object-oriented languages.

You use these to give your new objects their initial state. These 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;
}

Calling code:

MyClass myObject = new MyClass(100, 5);

Upvotes: 5

Muhammad Hasan Khan
Muhammad Hasan Khan

Reputation: 35156

Static constructor is called the first time your class is referenced i.e.

MyClass.SomeStaticMethod()

Instance constructor is called every time you do 'MyClass dummy = new MyClass()' i.e. create instance of the class

Semantically first is used when you want to ensure that some static state is initialized before it is accessed, the other is used to initialize instance members.

Upvotes: 11

Related Questions