What's Wrong With This Code?

Tuesday, August 1, 2006

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!";
    }
}


Comments
Joshua Flanagan Tuesday, August 1, 2006
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.
scott Tuesday, August 1, 2006
Correct, Joshua!
sergio giraldo Tuesday, August 1, 2006
The devious beforefieldinit metadata flag ?
RedBull Tuesday, August 1, 2006
This seems like a bug; the first line references the Child class and so should call the static constructor for Child.
Mark Lindell Wednesday, August 2, 2006
I believe a rule in code analysis will catch this. Study the CA rules! There is tons of stuff to learn in there.
Dan Wednesday, August 16, 2006
"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 are now closed.
by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!