What's Wrong With This Code?

The developer who wrote the following code expects to see "Hello World!" printed twice. What will the developer see, and why? (Hint: "Hello, World!" will only appear once).

using System;

class Program
{
    
static void Main()
    {
        
Console.WriteLine(Child.Message);
        
new Child();
        
Console.WriteLine(Child.Message);
    }
}

class Parent
{
    
static Parent()
    {
        _message =
"Hello!";
    }

    
static public string Message
    {
        
get { return _message; }
    }

    
static protected string _message;
}

class Child : Parent
{
    
static Child()
    {
        _message =
"Hello, World!";
    }
}

Print | posted @ Tuesday, August 01, 2006 2:30 AM

Comments on this entry:

Gravatar # re: What's Wrong With This Code?
by Joshua Flanagan at 8/1/2006 3:04 AM

Because for whatever reason, the C# compiler lets you reference static properties/methods using a descendent class name, even though it has nothing to do with the descendent class.

The "hello world" message isn't set until the Child static constructor is called, which isn't until the Child class is first used. The first call to Child.Message doesn't really reference the Child class - it is a straight passthrough to the Parent class.

This "feature" leads to so much confusion (this isn't the first quiz I've seen that takes advantage of the fact), it really should be a compiler error.
  
Gravatar # re: What's Wrong With This Code?
by scott at 8/1/2006 3:11 AM

Correct, Joshua!
  
Gravatar # re: What's Wrong With This Code?
by sergio giraldo at 8/1/2006 2:35 PM

The devious beforefieldinit metadata flag ?
  
Gravatar # re: What's Wrong With This Code?
by RedBull at 8/1/2006 4:13 PM

This seems like a bug; the first line references the Child class and so should call the static constructor for Child.
  
Gravatar # re: What's Wrong With This Code?
by Mark Lindell at 8/2/2006 12:59 PM

I believe a rule in code analysis will catch this. Study the CA rules! There is tons of stuff to learn in there.
  
Gravatar # re: What's Wrong With This Code?
by Dan at 8/16/2006 9:05 AM

"Because for whatever reason, the C# compiler lets you reference static properties/methods using a descendent class name, even though it has nothing to do with the descendent class."

I believe the reason is to enable you to make static methods "virtual".

Ive used it myself to provide a null-insensitive ToString static method in a base class, and to be able to override the default implementation easilly in some places.
  
Comments have been closed on this topic.