Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a static constructor not have any parameters?

Tags:

Per MSDN:

A static constructor does not take access modifiers or have parameters.

A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.

A static constructor cannot be called directly.

Can any one please explain why can't the static constructor have parameters?

like image 415
Simsons Avatar asked Jul 21 '11 06:07

Simsons


People also ask

Can static constructor have parameters?

A static constructor doesn't take access modifiers or have parameters. A class or struct can only have one static constructor. Static constructors cannot be inherited or overloaded. A static constructor cannot be called directly and is only meant to be called by the common language runtime (CLR).

What happens if we declare constructor as static?

If we declare a constructor as static, then it can not be accessed by its subclasses and will belong to a class level only. The program will not be compiled and throw a compile-time error.

Why are constructors always non static?

The statement super() is used to call the parent class(base class) constructor. This is the reason why constructor cannot be static – Because if we make them static they cannot be called from child class thus object of child class cannot be created.

What is the purpose of static constructor?

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.


2 Answers

As MSDN says, A static constructor is called automatically to initialize the class before the first instance is created. Therefore you can't send it any parameters.

If the CLR must call a static constructor how will it know which parameters to pass it?

like image 163
Motti Avatar answered Dec 23 '22 19:12

Motti


Static constructors are called automatically as part of type initialization. They're not called explicitly... so there's nowhere you could provide any arguments to correspond to the constructor parameters. Why would you want to allow parameters if you could never specify any values for the arguments?

like image 33
Jon Skeet Avatar answered Dec 23 '22 19:12

Jon Skeet