Is it possible to create a public static constructor at all?

There is a rule in Visual Studio 2012: Static constructors must be private , but the compiler does not allow this. Anyway, can we create a public static constructor?

enter image description here

Update: in the link: "If the static constructor is not private, it can be called by code other than the system." This brings me to this question.

+3


source to share


5 answers


You must omit the public

/ modifier private

:

public class Test
{
    static Test()
    {
    }
}

      

and actually the concept of a private

static constructor is a bit flimsy because a static constructor is called (and can be called) only by the CLR (runtime). Thus, it private

is probably only present because each method must have a modifier, and not because it means something (to make it clear: the class that defines it can call a private non-static constructor, while the static constructor cannot be directly called by the class that defines it)

Note that technically, by writing the IL directly, you can make a static constructor public

... Then you can call it as if it were a "normal" method ... and bad things happen ... To clarify this:

Basic source code:

using System;
using System.Linq;
using System.Reflection;

public class Program
{
    static void Main(string[] args)
    {
    }
}

public class Test
{
    static Test()
    {
        ConstructorInfo ci = typeof(Test).GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static).Single();
        Console.WriteLine("Static constructor: IsPublic: {0}, IsPrivate: {1}", ci.IsPublic, ci.IsPrivate);
    }
}

      

Compile it with Visual Studio.

From the developer command line:

ildasm YourExe.exe /out:test.il

      

Change Main

body to



.entrypoint
// Code size       2 (0x2)
.maxstack  8
IL_0000:  nop

// we call manually the cctor (the static constructor)
call void Test::.cctor()
IL_0001:  ret

      

then change the signature Test.cctor

to

.method public hidebysig specialname rtspecialname static 
      void  .cctor() cil managed

      

(see public

?)

Now

ilasm test.il
test.exe

      

Output:

Static constructor: IsPublic: True, IsPrivate: False
Static constructor: IsPublic: True, IsPrivate: False

      

The static constructor was executed twice: your call .cctor

plus the automatic call the CLR makes with .cctor

. Checking that the static constructor only runs once is only done when the CLR calls the static constructor, not when you manually call it! :-)

+7


source


Anyway, can we create a public static constructor?

No, you cannot, and you don't need to. Static constructors cannot be called and are not used like regular constructors. They are used internally by the runtime to initialize the static members of your class.



If the static constructor is not private, it can be called by code other than the system. ", it makes me ask this question.

Don't forget that code analysis is available for languages โ€‹โ€‹other than C # where it is possible that the static constructor is not private. Hence why this warning exists. In C # this will never happen.

+3


source


A static constructor has no access modifiers. Other static elements.

We can have static classes, fields, properties and methods denoted with an access modifier. But if you do it with a static constructor:

//Static class with Access Modifier
public class SomeClass
{
    //Static Field with Access Modifier
    public static int intstatic = 0;

    //Static Property with Access Modifier
    public static string StaticProperty { get; set; }

    //Trying to declare static Constructor with Access Modifier
    public static SomeClass()
    { }

    //Static Method with Access Modifier
    public static void DoSomething()
    {
        Console.WriteLine(intstatic);
    }
}

      

This will result in a compilation error.

"Access modifiers are not allowed on static constructors"

Haz, this will help you. walk through it, it will clear your foundations.

http://www.codeproject.com/Articles/891433/Must-Remember-Key-Concepts-to-Keyword-Static

+2


source


No, you cannot make a static constructor public or explicitly private in C # or VB.NET.

However, you could have done it in another programming language.

So, there is a rule to highlight these issues.

For C # and VB.NET, the rule will have no effect since you cannot break it.

Whether this will make a difference is debatable, as only the CLR can call a static constructor anyway, but that's why this rule exists.

+1


source


Access modifiers don't make sense in a static context. This is because they cannot be called directly by you, they are named implicitly by the .NET Framework.

It is guaranteed that your static constructor will be executed at some point in time prior to the first call to any static content .

You have no control over what this might practically be unchanged in practice just before you first access a static member. Don't rely on this though. Also note if your static constructor will change any state outside of its own class, as that could mean some very strange, flawless errors.

+1


source







All Articles