When I have class containing a static constructor, is that constructor called when the assembly containing the class is first loaded or when the first reference to that class is hit?
+6
A:
When the class is accessed for the first time.
Static Constructors (C# Programming Guide)
A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.
Developer Art
2009-09-17 08:00:06
Thanks, that makes sense when I think about it properly!
Jibberish
2009-09-17 08:10:03
+5
A:
This is a pretty good explanation. It's not quite as simple as you might expect!
Greg Beech
2009-09-17 08:02:57
A:
The static constructor is called before you use anything in the class, but exactly when that happens is up to the implementation.
It's guaranteed to be called before the first static member is accessed and before the first instance is created. If the class is never used, the static constructor is not guaranteed to be called at all.
Guffa
2009-09-17 08:23:26
When it happens *is not* "up to the implementation" if that implementation follows the ECMA C# spec: "The execution of a static constructor is triggered by the first of the following events to occur within an application domain: [1] An instance of the class is created. [2] Any of the static members of the class are referenced." (Section 17.11, http://www.ecma-international.org/publications/standards/Ecma-334.htm)
LukeH
2009-09-17 09:16:10
@Luke: "The exact timing of static constructor execution is implementation-dependent" http://ondotnet.com/pub/a/dotnet/2003/07/07/staticxtor.html
Guffa
2009-09-17 10:12:44
@Guffa: That might be the article author's interpretation, but you won't find that wording in the Microsoft or ECMA/ISO versions of the C# spec.
LukeH
2009-09-17 10:37:04