C # static constructor task

The following code does not call the static constructor of the class. Is this a bug or function?

class Test
{
    static Test
    {
       //do stuff
    }
    public static AnotherClass ClassInstance { get; set; }
}

class Program
{
    public static void Main()
    {
        var x = Test.ClassInstance;
    }
}

I don't have a compiler right now, but this is what happened to me today. A static constructor is never called, but it is called when ClassInstance is a field.

EDIT: I understand that the static constructor is called when the first instance is created or when the field is accessed. Isn't there a field behind an automatically implemented property?

I am looking for some explanation why a property does not call a static constructor when a property is implemented as two functions and one field. It is just very illogical for me, and that is why I thought it might be a mistake.

+3
source share
4 answers
+1

class Program
{
    static void Main(string[] args)
    {
        A.SomeField = new B();
    }
}

class A
{
    static A()
    {
        Console.WriteLine("Static A");
    }

    public static B SomeField { get; set; }
}

class B
{
    static B()
    {
        Console.WriteLine("Static B");
    }
}

:

Static B
Static A

- < B >

+1

I checked the same behavior, but if you change the code as follows:

class AnotherClass {}

class Test
{
    static Test()
    {
        Console.WriteLine("Hello, world!");
    }

    public static AnotherClass ClassInstance { get { return new AnotherClass(); } }

}

class Program
{
    public static void Main()
    {
        var x = Test.ClassInstance;
    }
}

he writes "Hello world!" ...

+1
source

The static constructor is called automatically before the first instance is created or any static members are referenced.

Additional information from Msdn.

0
source

Source: https://habr.com/ru/post/1774490/


All Articles