Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static constructor in C#

I am trying to use a static constructor like the following:

public static DataManager() {     LastInfoID = 1; } 

and getting this error:

access modifiers are not allowed on static constructors

I would like to know what's my problem.

like image 962
Nadav Avatar asked Nov 07 '10 19:11

Nadav


People also ask

Can we have static constructor?

No, we cannot define a static constructor in Java, If we are trying to define a constructor with the static keyword a compile-time error will occur. In general, static means class level. A constructor will be used to assign initial values for the instance variables.

What is difference between private and static constructor?

1. Static constructor is called before the first instance of class is created, wheras private constructor is called after the first instance of class is created. 2. Static constructor will be executed only once, whereas private constructor is executed everytime, whenever it is called.

What is static class in C?

A static class can only contain static data members, static methods, and a static constructor.It is not allowed to create objects of the static class. Static classes are sealed, means you cannot inherit a static class from another class. Syntax: static class Class_Name { // static data members // static method }

Are default constructors static?

Static constructor runs once per AppDomain just before you access the instance of class first time. You can use it to initialize static variables. On the other hand default constructor runs every time you create new instance of the class. in default constructor you can initialize non-static fields of the instance.


2 Answers

The static constructor has no access modifier: it is just:

static DataManager() // note no "public" {     LastInfoID = 1; } 

This is because it is never called explicitly (except perhaps via reflection) - but is invoked by the runtime; an access-level would be meaningless.

like image 95
Marc Gravell Avatar answered Sep 23 '22 02:09

Marc Gravell


The problem is that the LastInfoID field or property is not declared as static in your class and you can access only static members from a static constructor. Also remove the public keyword from the declaration:

static DataManager() {     LastInfoID = 1; } 
like image 36
Darin Dimitrov Avatar answered Sep 25 '22 02:09

Darin Dimitrov