Thursday, June 23, 2011

OPEN QUESTION : Are static classes provided default static constructor by compiler ?

ALMOST "NO".

http://msdn.microsoft.com/en-us/library/ms173115(v=vs.80).aspx
Unless the class is static, classes without constructors are given a public default constructor by the C# compiler in order to enable class instantiation.

http://msdn.microsoft.com/en-us/library/79b3xss3(v=vs.80).aspx
Static classes cannot contain a constructor, although it is still possible to declare a static constructor to assign initial values or set up some static state.

The first statements almost makes it clear, although it is not mentioned clearly anywhere that default static constructors are NOT provided by compiler to static classes.


Another intersesting thing, what if both a derived and base class have static constructors ?
see this : http://msdn.microsoft.com/en-us/library/k9x6w0hc(v=vs.80).aspx

Static constructor of derived class is called before base class's static constructor
When base class and derived class both have static contructors, then first derived class static constructor is called and then base class static constructor is called. (In C#.NET 2.0)
This is exactly opoosite to the instance constructor hierarchy.

No comments:

Post a Comment