Static constructor in C#
Solution 1
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.
Solution 2
Remove the public
. The syntax for a static constructor is:
class MyClass
{
static MyClass()
{
// Static constructor
}
}
Solution 3
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;
}
Solution 4
To give anyone here a more clear answer, without an example, think about why you would have to access a static constructor from outside? Static classes are created in memory upon application execution, that is why they are static. In other words, you would NEVER need to call one explicitly and if you do, say through reflection (which I don't know if it will let you), then you are doing something wrong.
When you create a new instance of a class, the constructor exists as a way to initialize all he internal variables and to do any kind of processing necessary to make the class function the way it is intended. Notice, if you do not specify a constructor the compiler will create one for you. For this reason you still need to create a class with a "()" like so
new MyClass();
because you are calling the default constructor (provided you do not have a parameterless one defined). In other words, the reason why a non-static constructor has to be defined as public is because you need to call it explicitly. If memory serves me well, C# will not compile on code that attempts to call a (through malloc) constructor that is not defined as public.
Constructors in a static class exist for "setup" purposes. For instance I can have a static class that is supposed to be the bridge between my code and a file that I am constantly saving and reading data from. I can define a constructor that, upon object creation, will make sure that the file exists and if not creates a default one (very help full in web systems that are ported to other servers).
Solution 5
using System;
public class Something
{
//
private static DateTime _saticConstructorTime;
private DateTime _instanceConstructorTime;
//
public static DateTime SaticConstructorTime
{
set { _saticConstructorTime = value; }
get { return _saticConstructorTime ; }
}
public DateTime InstanceConstructorTime
{
set { _instanceConstructorTime = value; }
get { return _instanceConstructorTime; }
}
//Set value to static propriety
static Something()
{
SaticConstructorTime = DateTime.Now;
Console.WriteLine("Static constructor has been executed at: {0}",
SaticConstructorTime.ToLongTimeString());
}
//The second constructor started alone at the next instances
public Something(string s)
{
InstanceConstructorTime = DateTime.Now;
Console.WriteLine("New instances: "+ s +"\n");
}
public void TimeDisplay(string s)
{
Console.WriteLine("Instance \""+ s + "\" has been created at: " + InstanceConstructorTime.ToLongTimeString());
Console.WriteLine("Static constructor has been created at: " + SaticConstructorTime.ToLongTimeString() + "\n");
}
}
//
class Client
{
static void Main()
{
Something somethingA = new Something("somethingA");
System.Threading.Thread.Sleep(2000);
Something somethingB = new Something("somethingB");
somethingA.TimeDisplay("somethingA");
somethingB.TimeDisplay("somethingB");
System.Console.ReadKey();
}
}
/* output :
Static constructor has been executed at: 17:31:28
New instances: somethingA
New instances: somethingB
Instance "somethingA" has been created at: 17:31:28
Static constructor has been created at: 17:31:28
Instance "somethingB" has been created at: 17:31:30
Static constructor has been created at: 17:31:28
*/
Related videos on Youtube
Nadav
Updated on December 10, 2020Comments
-
Nadav over 3 years
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.
-
user1703401 over 13 yearsLooks to me you should have asked "what is an access modifier?" Check your favorite C# language book. Now the error message becomes completely understandable.
-
Dykam over 13 years'access modifiers' ->
public
+ 'are not allowed' -> try removing it. IMO C# compilation messages are pretty clear. Lookup unknown terms using Google: google.nl/search?q=C%23+access+modifiers
-
-
Fredrik Mörk over 13 yearsFrom what I can tell based on the question the error was not at all related
LastInfoID
. Question might have been edited though. -
Guffa over 13 yearsThere is nothing that suggests that
ListInfoID
is not static. -
Darin Dimitrov over 13 yearsYes, I was wrong. It is related to the
public
modifier. Sorry for that. -
paraJdox1 over 3 yearswhat is the default access modifier for static constructors? is it public too?
-
Marc Gravell over 3 years@Hacki static constructors don't have access modifiers (and you cannot add one); you don't call them - the runtime does, and the runtime doesn't need any kind of special access; in terms of the IL generated,
.cctor
is markedprivate
: sharplab.io/… -
paraJdox1 over 3 yearsI'm just curious @marc gravell, because it says here: youtube.com/watch?v=KZ1b37S1mbY (@8:05) that "static constructors are by default public"; and in this link: quora.com/… most of the answers are "private" so I was just a bit confused. Thank you for the clarification.
-
paraJdox1 over 3 yearsI can't really real the IL that is generated, in which part does it say that its private? this ".class public auto ansi C" says that its public though
-
Marc Gravell over 3 years@Hacki the class is
public
(as inpublic class C
); the static constructor isprivate
; the video you've linked to is simply wrong - twice, in fact: a) because it claims they are public (which they aren't), and b) because they suggest that this is "by default", which is ... meaningless: this is the only option -
Marc Gravell over 3 years@Hacki btw, the bit that says that the static constructor is private is this:
.method private hidebysig specialname rtspecialname static void .cctor () cil managed
- that defines a method (.method
) and note that it is bothstatic
andprivate
; there's a runtime recognised convention (hidebysig specialname rtspecialname
means "look for special names - they're not accidental") that.cctor
is a special name that defines the "static constructor" (actually, the "type initializer" in IL terms - it can include code not in the C# static constructor, such as static field initializers) -
paraJdox1 over 3 yearshow about this one: .method public hidebysig specialname rtspecialname instance void .ctor () cil managed ? its public... what does this mean?
-
Marc Gravell over 3 years@Hacki that (
.ctor
, note only onec
) is the instance constructor; in a non-static class, if you don't add any constructors, the compiler adds a default constructor similar to:public MyClass() {}
-
paraJdox1 over 3 yearsThank you so much Sir @Marc Gravell this is so insightful!