473,761 Members | 9,864 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

BUG in static constructors?!? !?

Hi all,
According C# Language Specification :

10.11 Static constructors:

The static constructor for a class executes at most once in a given
application domain. The execution of a static constructor is triggered
by the first of the following events to occur within an application
domain:
- An instance of the class is created.
- Any of the static members of the class are referenced.

Then can someone confirm that the following code does not act as it
should (seems like a bug), i.e. static constructor is NEVER called.

Pls, note that if you uncomment the first line in Main(), everything
runs as expected.

Also, my environment is VS.Net 2003/framework 1.1.

Thanks
Sunny

CODE (watch out for line wraps):

using System;
using System.Net;
using System.IO;

namespace TestApp
{
class TestApp
{
[STAThread]
static void Main(string[] args)
{
//MyChildClass.Th eString = "Set";
MyChildClass.Do Something();
Console.WriteLi ne("Press enter to continue");
Console.ReadLin e();
}
}

public abstract class MyBaseClass
{
protected delegate void DoSomethingDele gate();

protected static DoSomethingDele gate DoSomethingFunc ;

protected static string SomeString = "N/A";

public static void DoSomething()
{
Console.WriteLi ne("MyBase.DoSo mething()");
DoSomethingFunc ();
}
}

public class MyChildClass : MyBaseClass
{
static MyChildClass()
{
Console.WriteLi ne("static MyChildClass()" );
DoSomethingFunc =
new DoSomethingDele gate(DoSomethin gImpl);
}

protected static void DoSomethingImpl ()
{
Console.WriteLi ne("DoSomething ()");
}

public static string TheString
{
get{return SomeString;}
set{SomeString = value;}
}

}
}

Nov 15 '05 #1
7 1877
DoSomething() is a member of MyBaseClass, even though C# allows you to
access it via MyChildClass. Therefore no member of MyChildClass is
referenced. I actually like this behaviour, because it gives you more
granular control over static constructor execution for 'lazy' construction
of singletons etc. What I'm not certain I like is C# giving you access to a
public static member of a base type, when it removes all reference to the
type your are specifying in the IL (I looked and MyBaseClass gets called in
the IL, so it's definately C# doing this). I'll have to look up where this
behaviour is specified, as maybe there's a clue as to why it's this way.

But anyway, keep in mind there are other constructs in which you can refer
to MyChildClass that don't result in the static constructor being fired, as
well, i.e. typeof(MyChildC lass), so I ultimately I think it's fair that base
class members should not cause the constructor to fire.

Richard

--
Veuillez m'excuser, mon Français est très pauvre. Cependant, si vous voyez
mauvais C #, c'est mon défaut!
"Sunny" <su******@icebe rgwireless.com> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Hi all,
According C# Language Specification :

10.11 Static constructors:

The static constructor for a class executes at most once in a given
application domain. The execution of a static constructor is triggered
by the first of the following events to occur within an application
domain:
- An instance of the class is created.
- Any of the static members of the class are referenced.

Then can someone confirm that the following code does not act as it
should (seems like a bug), i.e. static constructor is NEVER called.

Pls, note that if you uncomment the first line in Main(), everything
runs as expected.

Also, my environment is VS.Net 2003/framework 1.1.

Thanks
Sunny

CODE (watch out for line wraps):

using System;
using System.Net;
using System.IO;

namespace TestApp
{
class TestApp
{
[STAThread]
static void Main(string[] args)
{
//MyChildClass.Th eString = "Set";
MyChildClass.Do Something();
Console.WriteLi ne("Press enter to continue");
Console.ReadLin e();
}
}

public abstract class MyBaseClass
{
protected delegate void DoSomethingDele gate();

protected static DoSomethingDele gate DoSomethingFunc ;

protected static string SomeString = "N/A";

public static void DoSomething()
{
Console.WriteLi ne("MyBase.DoSo mething()");
DoSomethingFunc ();
}
}

public class MyChildClass : MyBaseClass
{
static MyChildClass()
{
Console.WriteLi ne("static MyChildClass()" );
DoSomethingFunc =
new DoSomethingDele gate(DoSomethin gImpl);
}

protected static void DoSomethingImpl ()
{
Console.WriteLi ne("DoSomething ()");
}

public static string TheString
{
get{return SomeString;}
set{SomeString = value;}
}

}
}

Nov 15 '05 #2
Hi Richard,
Thanks for posting. Please read inline.

In article <OD************ **@TK2MSFTNGP10 .phx.gbl>,
ch*****@yumspam yumYahoo.com says...
DoSomething() is a member of MyBaseClass, even though C# allows you to
access it via MyChildClass. Therefore no member of MyChildClass is
referenced. I actually like this behaviour, because it gives you more
granular control over static constructor execution for 'lazy' construction
of singletons etc. What I'm not certain I like is C# giving you access to a
public static member of a base type, when it removes all reference to the
type your are specifying in the IL (I looked and MyBaseClass gets called in
the IL, so it's definately C# doing this). I'll have to look up where this
behaviour is specified, as maybe there's a clue as to why it's this way.
I'm still confused, as the MyBase is abstract, I.e. it purpose is
exactly to be used as base, not directly. But I have checked, you can
invoke a static member of abstract class?!? Yes, its written, that you
can not create an object of that class, and nothing about static
members, but still a little bit messy IMHO. I'm not surprised that in IL
there is reference to MyBaseClass.Sta ticMember, as in spec is written,
that there is exactly one storage location. No matter how many instances
of a class are created, there is only ever one copy of a static field.
But this still does not mean that that member is not member of the child
class.
Or I'm wrong?

And my understanding is (uhh, was :) ) that inheritance is that, the new
class just contains the base one, or at least acts like this. In the
spec (10.2.1) explicitly is written:
"A class inherits the members of its direct base class. Inheritance
means that a class implicitly contains all members of its direct base
class".
If there was written, something like refers, not contains, I could
accept that these members are not part of the child class.

I'm not against the behaviour, I was just surprised that this do not
correspond to the specs, or maybe the spec is not clear, or ... who
knows ...

Actually, if MS confirms that this is exactly what they had in mind, it
should be stated more clearly.


But anyway, keep in mind there are other constructs in which you can refer
to MyChildClass that don't result in the static constructor being fired, as
well, i.e. typeof(MyChildC lass), so I ultimately I think it's fair that base
class members should not cause the constructor to fire.
About typeof(), when you invoke it, still there is no reference to any
member of the class, so I also would not expect static constructor to be
fired.

Richard

Anyway, do you have any idea how to accomplish such a behavior.
My goal is to create a base class for logging, which I can use in all my
..Net apps - webservices, winforms, console apps, etc. I need to invoke
the logging function from everywhere, so static is the way :)
I have created a custom Attribute class, and in the DoSomething() I
check if the calling method is marked as a method which can (have to) be
logged, so I can put this attribute only to methods which I'm currently
interested in.

As the method which will actually write the message in the log, will be
different for every app, I wanted only to recreate that method, while
all other checks before that to be implemented in the base. I can not
make that method abstract, as I want it to be static, and there is no
way to use static abstract :(

I just tried that approach, assuming that static constructor will be
invoked to hook the method.

Any clue? I just want to place wherever I want MyChild.DoSomet hing(),
and actually to use the DoSomethingFunc () only if some checks (for
attribute, etc) are true in DoSomething.

Thanks again for reading this.
Sunny
Nov 15 '05 #3
> But this still does not mean that that member is not member of the child
class.
Or I'm wrong?
This is why I was a bit surprised that the child class exposed the base
member - since it seems to imply that it works the same way as an instance
member (an instance member in MyBaseClass, whether virtual or not, will
cause the static constructor of MyChildClass to fire if called).
Actually, if MS confirms that this is exactly what they had in mind, it
should be stated more clearly.
Yes, I agree, it's a somewhat ambiguous, IMO.

Richard

--
Veuillez m'excuser, mon Français est très pauvre. Cependant, si vous voyez
mauvais C #, c'est mon défaut!
"Sunny" <su******@icebe rgwireless.com> wrote in message
news:MP******** *************** *@msnews.micros oft.com... Hi Richard,
Thanks for posting. Please read inline.

In article <OD************ **@TK2MSFTNGP10 .phx.gbl>,
ch*****@yumspam yumYahoo.com says...
DoSomething() is a member of MyBaseClass, even though C# allows you to
access it via MyChildClass. Therefore no member of MyChildClass is
referenced. I actually like this behaviour, because it gives you more
granular control over static constructor execution for 'lazy' construction of singletons etc. What I'm not certain I like is C# giving you access to a public static member of a base type, when it removes all reference to the type your are specifying in the IL (I looked and MyBaseClass gets called in the IL, so it's definately C# doing this). I'll have to look up where this behaviour is specified, as maybe there's a clue as to why it's this way.


I'm still confused, as the MyBase is abstract, I.e. it purpose is
exactly to be used as base, not directly. But I have checked, you can
invoke a static member of abstract class?!? Yes, its written, that you
can not create an object of that class, and nothing about static
members, but still a little bit messy IMHO. I'm not surprised that in IL
there is reference to MyBaseClass.Sta ticMember, as in spec is written,
that there is exactly one storage location. No matter how many instances
of a class are created, there is only ever one copy of a static field.
But this still does not mean that that member is not member of the child
class.
Or I'm wrong?

And my understanding is (uhh, was :) ) that inheritance is that, the new
class just contains the base one, or at least acts like this. In the
spec (10.2.1) explicitly is written:
"A class inherits the members of its direct base class. Inheritance
means that a class implicitly contains all members of its direct base
class".
If there was written, something like refers, not contains, I could
accept that these members are not part of the child class.

I'm not against the behaviour, I was just surprised that this do not
correspond to the specs, or maybe the spec is not clear, or ... who
knows ...

Actually, if MS confirms that this is exactly what they had in mind, it
should be stated more clearly.


But anyway, keep in mind there are other constructs in which you can refer to MyChildClass that don't result in the static constructor being fired, as well, i.e. typeof(MyChildC lass), so I ultimately I think it's fair that base class members should not cause the constructor to fire.


About typeof(), when you invoke it, still there is no reference to any
member of the class, so I also would not expect static constructor to be
fired.

Richard

Anyway, do you have any idea how to accomplish such a behavior.
My goal is to create a base class for logging, which I can use in all my
.Net apps - webservices, winforms, console apps, etc. I need to invoke
the logging function from everywhere, so static is the way :)
I have created a custom Attribute class, and in the DoSomething() I
check if the calling method is marked as a method which can (have to) be
logged, so I can put this attribute only to methods which I'm currently
interested in.

As the method which will actually write the message in the log, will be
different for every app, I wanted only to recreate that method, while
all other checks before that to be implemented in the base. I can not
make that method abstract, as I want it to be static, and there is no
way to use static abstract :(

I just tried that approach, assuming that static constructor will be
invoked to hook the method.

Any clue? I just want to place wherever I want MyChild.DoSomet hing(),
and actually to use the DoSomethingFunc () only if some checks (for
attribute, etc) are true in DoSomething.

Thanks again for reading this.
Sunny

Nov 15 '05 #4
Sunny <su******@icebe rgwireless.com> wrote:
I'm still confused, as the MyBase is abstract, I.e. it purpose is
exactly to be used as base, not directly. But I have checked, you can
invoke a static member of abstract class?!?
Absolutely - why would you not be able to?
Yes, its written, that you
can not create an object of that class, and nothing about static
members, but still a little bit messy IMHO.
Why? One of the common patterns in OO is to have a publicly available
abstract class which provides a factory method to return an instance of
a derived class which the caller may not know about directly. Look at
Encoding.GetEnc oding as an example of that.
I'm not surprised that in IL
there is reference to MyBaseClass.Sta ticMember, as in spec is written,
that there is exactly one storage location. No matter how many instances
of a class are created, there is only ever one copy of a static field.
But this still does not mean that that member is not member of the child
class.
Or I'm wrong?
The spec isn't terribly clear on this. According to 17.2.5 (I'm using
ECMA numbering, btw) "When a static member is referenced in a member-
access (§14.5.4) of the form E.M, E must denote a type that has a
member M." which would imply that the static method *was* a member of
the derived class.
And my understanding is (uhh, was :) ) that inheritance is that, the new
class just contains the base one, or at least acts like this. In the
spec (10.2.1) explicitly is written:
"A class inherits the members of its direct base class. Inheritance
means that a class implicitly contains all members of its direct base
class".
If there was written, something like refers, not contains, I could
accept that these members are not part of the child class.

I'm not against the behaviour, I was just surprised that this do not
correspond to the specs, or maybe the spec is not clear, or ... who
knows ...
The specs are indeed unclear, unfortunately. I'm pretty sure the
behaviour exhibited is the intended one, but it's not very clearly
stated as far as I can see.
Anyway, do you have any idea how to accomplish such a behavior.
My goal is to create a base class for logging, which I can use in all my
.Net apps - webservices, winforms, console apps, etc. I need to invoke
the logging function from everywhere, so static is the way :)
I have created a custom Attribute class, and in the DoSomething() I
check if the calling method is marked as a method which can (have to) be
logged, so I can put this attribute only to methods which I'm currently
interested in.

As the method which will actually write the message in the log, will be
different for every app, I wanted only to recreate that method, while
all other checks before that to be implemented in the base. I can not
make that method abstract, as I want it to be static, and there is no
way to use static abstract :(

I just tried that approach, assuming that static constructor will be
invoked to hook the method.

Any clue? I just want to place wherever I want MyChild.DoSomet hing(),
and actually to use the DoSomethingFunc () only if some checks (for
attribute, etc) are true in DoSomething.


To be honest, I'm still not sure about where the derived class comes in
- surely as soon as you have more than one of those derived classes,
things come unstuck anyway, don't they, as you'd be resetting
DoSomethingFunc .

I've a feeling the singleton pattern *may* be useful to you, but
without understanding your problem better it's hard to say for sure.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #5
Hi Jon, thanks for posting.
Pls, read inline
Why? One of the common patterns in OO is to have a publicly available
abstract class which provides a factory method to return an instance of
a derived class which the caller may not know about directly. Look at
Encoding.GetEnc oding as an example of that. It seems I have missed something in my education (as usual :) ). May you
give some examples of implementation, or starting point?
The spec isn't terribly clear on this. According to 17.2.5 (I'm using
ECMA numbering, btw) "When a static member is referenced in a member-
access (§14.5.4) of the form E.M, E must denote a type that has a
member M." which would imply that the static method *was* a member of
the derived class. And, if it IS a member of the derived class, why the ctor is not fired?
The specs are indeed unclear, unfortunately. I'm pretty sure the
behaviour exhibited is the intended one, but it's not very clearly
stated as far as I can see. Am I missing something in the theory and practice of OO, which should
explain why this have to be intended?
To be honest, I'm still not sure about where the derived class comes in
- surely as soon as you have more than one of those derived classes,
things come unstuck anyway, don't they, as you'd be resetting
DoSomethingFunc . Yes, you are right, but I can not think about anything else.
I've a feeling the singleton pattern *may* be useful to you, but
without understanding your problem better it's hard to say for sure.


This is only for internal use, I want to have the same (or :) mostly the
same) log mechanism in all my apps, and to rewrite only the way actual
log is stored.
So it seems that there can be 2 ways from that point - singleton pattern
(I have to read :) ), or not to use static ctor, but any static method
which will attach the delegate.

Thanks again for the posting
Sunny
Nov 15 '05 #6
Sunny <su******@icebe rgwireless.com> wrote:
Why? One of the common patterns in OO is to have a publicly available
abstract class which provides a factory method to return an instance of
a derived class which the caller may not know about directly. Look at
Encoding.GetEnc oding as an example of that.
It seems I have missed something in my education (as usual :) ). May you
give some examples of implementation, or starting point?
Okay, very simple implementation example for WebRequest. I'm not saying
this is what *actually* happens, but it might be close:

public WebRequest Create (string uri)
{
if (uri.StartsWith ("http:"))
return new HttpWebRequest (uri);
if (uri.StartsWith ("ftp:"))
return new FtpWebRequest (ur);
...
}

It means the client doesn't need to know about the derived classes
directly.
The spec isn't terribly clear on this. According to 17.2.5 (I'm using
ECMA numbering, btw) "When a static member is referenced in a member-
access (§14.5.4) of the form E.M, E must denote a type that has a
member M." which would imply that the static method *was* a member of
the derived class. And, if it IS a member of the derived class, why the ctor is not fired?
Well that's the trick - it's really only "sort of" a member itself; as
we've seen, the compiled code has no mention of the base class.
The specs are indeed unclear, unfortunately. I'm pretty sure the
behaviour exhibited is the intended one, but it's not very clearly
stated as far as I can see. Am I missing something in the theory and practice of OO, which should
explain why this have to be intended?
Well, you're actually calling the base method, and as it's a static
method there's no possibility of it being overridden, so no polymorphic
behaviour is needed. As far as everything apart from class
initialisation might be concerned, it is exactly the same as calling
the base class's method - so that's what it gets turned into,
unfortunately for you.
To be honest, I'm still not sure about where the derived class comes in
- surely as soon as you have more than one of those derived classes,
things come unstuck anyway, don't they, as you'd be resetting
DoSomethingFunc . Yes, you are right, but I can not think about anything else.

I've a feeling the singleton pattern *may* be useful to you, but
without understanding your problem better it's hard to say for sure.


This is only for internal use, I want to have the same (or :) mostly the
same) log mechanism in all my apps, and to rewrite only the way actual
log is stored.
So it seems that there can be 2 ways from that point - singleton pattern
(I have to read :) ), or not to use static ctor, but any static method
which will attach the delegate.


Here's some info about singletons which you might find useful:

http://www.pobox.com/~skeet/csharp/singleton.html

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #7
Thanks Jon,
very usefull.

Sunny
Nov 15 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
3659
by: javac | last post by:
for better or worse, my free time is consumed by two Java series books from Sun: Java Platform Performance, 2000, by Wilson and Kesselman Effective Java, 2001, by Bloch 1.) opinions on these books? good/bad/mediocre/great/etc? are they up to date, or out of date? 2.) please do check out my code at
3
18815
by: Amit | last post by:
is there anything like static constructors or destructors in C++ ? if yes, how to implement it? Thanks, Amit.
7
17194
by: mdc | last post by:
Hi, Is there any way to implement an interface as a static method in C#? If not, is this a bug? Micheal.
9
2430
by: A J Le Couteur Bisson | last post by:
Could someone please confirm that static class constructors are only called at the first use of a non-static constructor on the class, or am I doing something wrong? If this is indeed the case then I would consider this a serious error in the language implementation, not to mention a pain in the backside :( Also, is it to much to ask that the method Type.GetTypeFromCLSID be documented
6
5896
by: ~~~ .NET Ed ~~~ | last post by:
Yes, I think so at least... In C# you *can* have static properties which are quite useful when used properly. Now imagine the scenario where you need the ability (sp?) to implement a variety of classes that must implement an interface. All these classes must have a particular *static* property, and this in particular is handy not only to be consequent with the fact that you can do it with classes but also with the fact that you cannot...
17
2354
by: Picho | last post by:
Hi all, I popped up this question a while ago, and I thought it was worth checking again now... (maybe something has changed or something will change). I read this book about component oriented design (owreilly - Juval Lowy), and it was actually very nice. The book goes on about how we should use Interfaces exposure instead of classes (this is my terminology and english is not my language so I hope you understand what I'm on about...).
12
3441
by: Hemanth | last post by:
Hi, I have a base class with a static constructor and some abstract methods. Derived classes implement these methods. From articles on the web, it appears that there is no guarentee that this static constructor of the base class would be invoked even if a an object of the derived class is created. Is this correct ? Is there any way to ensure the base class's static constructor is invoked before the derived class instance is constructed ?...
3
1405
by: Jordan S. | last post by:
Just learning OOP here... Does it make sense to have a constructor in a static class? Say I have a class with a constructor and then mark that class as static; will it (the default constructor) get called when the application starts? or are any/all constructors ignored in static classes? Thanks.
3
4360
by: Adam | last post by:
What happens if one thread is executing a static constructor and another thread starts. Does the second thread block until the first is done in the static constructor? I want to make sure all my globals are initialized and the second thread does not throw an exception. Thanks in advance. Adam Smith
2
2002
by: Tim Van Wassenhove | last post by:
Hello, When i read the CLI spec, 8.10.2 Method inheritance i read the following: "A derived object type inherits all of the instance and virtual methods of its base object type. It does not inherit constructors or static methods...." In the C# spec, 17.2.1 Inheritance i read the following:
0
9345
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9957
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9905
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9775
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7332
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6609
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5229
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
3456
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2752
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.