Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In .NET, are static constructors called when a new AppDomain is created?

Tags:

c#

appdomain

When I create a new AppDomain using AppDomain.CreateDomain in C#, will static constructors be called as asseblies are loaded inside the newly created AppDomain?

The assemblies in question have already been loaded into the current domain.

like image 399
ngoozeff Avatar asked Aug 13 '10 07:08

ngoozeff


People also ask

When and how is static constructor called?

A static constructor is called automatically. It initializes the class before the first instance is created or any static members declared in that class (not its base classes) are referenced. A static constructor runs before an instance constructor.

Which of the following statement is true about static constructors?

Which of the following statements is correct about constructors in C#.NET? Explanation: Static constructor is a constructor which can be called before any object of class is created or any static method is invoked.

Which constructor is called first in C# static or default?

That's why you can see in the output that Static Constructor is called first. Times of Execution: A static constructor will always execute once in the entire life cycle of a class. But a non-static constructor can execute zero time if no instance of the class is created and n times if the n instances are created.


2 Answers

No - static constructors will only be called the first time a static member is accessed or an instance is created.

The static constructor will be invoked once per AppDomain though, if that's what you were concerned about. It's not like having executed once in a different AppDomain, the types in the new AppDomain get left uninitialized :)

Note that type initializers for types without static constructors may be executed earlier or later than those for types with static constructors, and the precise implementation details changed for .NET 4.

like image 108
Jon Skeet Avatar answered Oct 01 '22 17:10

Jon Skeet


Check this site: http://codeidol.com/csharp/net-framework/Threads,-AppDomains,-and-Processes/AppDomains/

Here is an excerpt:

Unless you use something like thread-static fields, each AppDomain contains a copy of all static fields. All class (or static) constructors will run once within a given AppDomain. This means that if you load the same assembly in different AppDomains, each will run the class constructors, and each will contain separate values for all static fields, for example.

like image 37
spinon Avatar answered Oct 01 '22 19:10

spinon