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.
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 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.
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.
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.
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.
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