Re: static constructor in derived class not being called

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



Elia,

Interesting stuff!

My guess is:
a) Before the call to MyDerived.DoSomething(), the CLR loads MyDerived and
immediately executes static constructor
b) Because of the inheritance relationship, the CLR loads MyBase, and
immediately initializes static field to 0 and then executes static
constructor (which in this case does nothing).
c) The call to DoSomething() proceeds, printing 0...

Regards - Octavio

"Elia Karagiannis" <ekaragiannis@xxxxxxxxxxxxx> escribió en el mensaje
news:uYJzqQEnFHA.2484@xxxxxxxxxxxxxxxxxxxxxxx
> The static constructor of a derived class never gets called if it has no
> other methods and the base class is only static
>
> I have the following base class and derived class.
>
> public class MyBase
> {
> protected MyBase()
> {}
>
> protected static int x;
>
> public static void DoSomething()
> {
> Console.WriteLine("X = " + x.ToString());
> }
> }
>
>
> // the derived class
> public class MyDerived : MyBase
> {
> static MyDerived()
> {
> x = 5;
> }
> }
>
> static void Main()
> {
> MyDerived.DoSomething(); // prints out zero instead of 5
> // the static
> constructor on the derived class never gets called
> // if I add a dummy
> static method to the derived class and call it then the
> // static
> constructor of the derived class will be called but I cant do this...
> }
>
>
> Any suggestions or can this just not be done??
>


.



Relevant Pages

  • Re: getting used to Java - question about "style"
    ... > I am reading a book that a collegue gave me called "The Elements of Java ... > before executing the derived class constructors. ... > constructor." ... void print() { ...
    (comp.lang.java.programmer)
  • :: Scope qualifier misunderstanding.
    ... arguments from the derived constructor). ... I was hoping this would set the values in the derived class using the ... (inherits base2). ... // Base 2 declaration, ...
    (comp.lang.cpp)
  • Re: static constructor in derived class not being called
    ... I thought DoSomething was defined in MyDerived... ... > constructor. ... >> I have the following base class and derived class. ... >> public class MyBase ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: templates and inheritance
    ... I have learned the derived class does not automatically inherit the ... > base class constructors, and attempts to create new functions to work on ... Since the derived class constructor are ... > Did I miss something when I did my inheritance? ...
    (alt.comp.lang.learn.c-cpp)
  • Re: What replace "this" in static class?
    ... Originally, your class, as a derived class of QuickFix.Application, ... > function to do the constructor job. ... > This class inherit from a QuickFix.Application class. ... > And previously I was using "this" keyword because the class inherit ...
    (microsoft.public.dotnet.languages.csharp)