Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe for a class to create instances of itself inside the static constructor?

Tags:

c#

I stumbled upon a problem where i need an instance of the class inside its static constructor. I believed it was not possible to do it so i tried the following:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(Foo.someString);
        Console.ReadLine();
    }
}

class Foo
{
    public static readonly string someString;

    static Foo()
    {
        someString = new Foo().CreateString();
    }

    private string CreateString()
    {
        return "some text";
    }
}

To my surprise, it works - the output is "some text". I believed the static constructor must run and complete before instances of the class can be created. This answer shows that this is not necessarily the case. Does this mean that static and instance constructors are independent of each other? And finally, is it safe to do this (create instances in static constructor)?

p.s. Let's ignore the fact that this can be avoided by using a different approach.

like image 672
loodakrawa Avatar asked Feb 20 '12 09:02

loodakrawa


People also ask

Can a instance class have static constructor?

A class or struct can only have one static constructor. Static constructors cannot be inherited or overloaded. A static constructor cannot be called directly and is only meant to be called by the common language runtime (CLR). It is invoked automatically.

Can static classes have instances?

Static classes cannot contain an instance constructor. However, they can contain a static constructor. Non-static classes should also define a static constructor if the class contains static members that require non-trivial initialization.

Which statement is true about static constructor?

Which among the following is true for static constructor? Explanation: Static constructors can't be parameterized constructors.

Can you have multiple instances of a static class?

A static class cannot be instantiated. All members of a static class are static and are accessed via the class name directly, without creating an instance of the class. The following code is an example of a static class, CSharpCorner. We know that all members of the class are static.


1 Answers

All that the specification says is that the static constructor will be called before any instance of the class is created. But it doesn't state anything about the fact that this constructor must finish:

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.

You could perfectly fine create instances of the class inside the static constructor and this is safe.

like image 53
Darin Dimitrov Avatar answered Oct 06 '22 20:10

Darin Dimitrov