Default static constructor?

Well, I'm confused. I am using MDbgEngine to analyze an application. This is working well; I set breakpoints on the.ctor method of each class at load time, so I know when an instance of each class is constructed. This works adequately using the default constructor, so even if no constructor is explicitly implemented in the code, my analysis works.

However ... in the case of a class containing only static members (say, the defaultProgram class of a console app created in VS2005), the default static constructor.cctor isnot called - I have to explicitly implement a static constructor in theProgram class.

I don't understand why this is; using Lutz Roeder's Reflector I can see the default static constructor ... it just doesn't get called, whereas if I add a static constructor to the code, thatdoes get called

If anyone can shed some light on this, I'd be greatly appreciative.

[1028 byte] By [DuncanBayne] at [2008-1-13]
# 1

The static constructors (cctor) can be called lazily. If you use a field initialized in the static ctor, then you should see the ctor invoked.

See here for more details: http://blogs.msdn.com/davidnotario/archive/2005/02/08/369593.aspx

In the same way, you may notice that inspecting not-yet-used static variables with ICorDebug may fail with CORDBG_E_STATIC_VAR_NOT_AVAILABLE.

The fact that cctors are invoked at 'unpredictable' times also makes stepping interesting (when does step-in land at the cctor?). There's some interesting discussion of that here: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=599632&SiteID=1 and here http://blogs.msdn.com/jmstall/archive/2005/07/26/stepin_is_not_well_defined.aspx

Hope that helps!

MikeStall-MSFT at 2007-8-30 > top of Msdn Tech,.NET Development,Building Development and Diagnostic Tools for .Net...

.NET Development

Site Classified