Alex Rivera | Logout

Static constructor in C#

Asked 2010-11-07T19:47:19.030
50

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.

Edit
Report

1 Answer

5

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).

answered 2013-01-22T16:16:10.910

Your Answer