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.
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.
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 among the following is true for static constructor? Explanation: Static constructors can't be parameterized constructors.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With