Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# static garbage collector?

I have a simple class which has a static constructor and a instance constructor. Now when i initialized the class , both static and instance constructor are called. Only static is referred once in a application domain . Can i again call the same class initialization and static constructor initialize again? I have tried but it didn't happen? Is there any way we can call static constructor again in main() method after using garbage collection on the class.

Here is the code:

public class Employee
{
    public Employee()
    {
        Console.WriteLine("Instance constructor called");   
    }

    static Employee()
    {
        Console.WriteLine("Static constructor called");   
    }

    ~Employee()
     {
        //Dispose();
     }
}

Now in main method call:

static void Main(string[] args)
{
    Employee emp = new Employee();
    Employee emp = new Employee();
}

Output:

Static constructor called Instance constructor called Instance constructor called

Now the static didn't called again. Because it is called once in application domain. But is their any way we could call it again without unloading application domain. Can we use GC class over here?

Thanks. Pal

like image 678
A.P.S Avatar asked Dec 21 '22 23:12

A.P.S


2 Answers

Unless you prod it with reflection, the static constructor (or more generally, the type initializer) is only executed once per concrete class, per AppDomain.

Note that for generics, using different type arguments you'll get different concrete classes:

public class Foo<T>
{
    Foo()
    {
        Console.WriteLine("T={0}", typeof(T));
    }
    public static void DummyMethod() {}
}
...
Foo<int>.DummyMethod(); // Executes static constructor first
Foo<string>.DummyMethod(); // Executes static constructor first
Foo<string>.DummyMethod(); // Type is already initialized; no more output
like image 124
Jon Skeet Avatar answered Dec 24 '22 13:12

Jon Skeet


Not possible. The CLR keeps an internal status bit that tracks whether the type initializer was started. It cannot run again. That status bit is indeed stored in the loader heap as part of the AppDomain state. The workaround is simple, just add a static method to the class.

like image 45
Hans Passant Avatar answered Dec 24 '22 12:12

Hans Passant