Overload Static Methods Inheritance: A Bug Story

time to read 3 min | 571 words

Today I had a bug, a very nasty one. This bug was quite innocent, is looked like this:

Animal animal = Poodle.Black("My Doggie");

A pretty simple code, isn't it? The Black() method is a static method that just creates the object (its purpose is to simplify instansiating the object, nothing more). But instead of getting a poodle, I was getting a generic dog!

The sad part about it is that it worked when I was trying to save it, and only bombed when I tried to load it, meaning that I got the exception on a totally unrelated place in my code. After indiscrimantely accusing (roughly in this order):

  1. Castle.ActiveRecord
  2. NHibernate
  3. Sql Server
  4. TCP Stack
  5. The Cat
  6. The Little Green Men
  7. That Guy Over There

I sat down and really looked at at, and I still couldn't find a reason that this would give the end result. The Poodle class obviously had a static Black() method, in which a Poodle was created and returned. Why was I having this problem? What did I do to deserve this?

Well, I did something very stupid, let's see if you can figure this out from the code:

public class Dog : Animal
{
   public static Dog Black(string name) 
   {
      return new Dog(name, Color.Black);
   }
}
public class Poodle : Dog
{
    public new static Poodle Black(string name, bool isNasty)
    {
         return new Poodle(name, isNasty, Color.Black);
     }
}

Do you see the problem? I was using the wrong overload, and the method that the compiler called was Dog.Black(). Finding out that it was my fault didn't go very well with the Cat, I can tell you that.

Anyway, the lesson is that you should be careful about "overriding" static methods, because they can bite.