Static Cling? No, Static Wierdness.

I thought this was a little odd. As you may or may not know, static (Shared in VB.NET) members are not inherited. Since static members are members of the class, not an instance of the class, this makes sense. When you create a subclass, you're creating a new class so you don't get the static methods.

However, the compiler still lets you access the static methods of your base class. Example:

using System;

namespace InheritStaticsExample
{
	public class Foo
	{
		public static void Pack() 
		{
		}
	}

	public class Bar : Foo
	{
	}


	public class Test
	{
		public Test()
		{
			Bar.Pack();
		}
	}
}

This code compiles just fine. If you pull out ILDASM (or your disassembler of choice), you'll see that the call to Bar.Pack() is compiled into a call to Foo.Pack(). Kind of wierd. If I can't inherit static members, why can I call them from my subclass?

Now lets makes things a little more interesting. Suppose we add a static Pack() method to Bar. Then what happens?

using System;

namespace InheritStaticsExample
{
	public class Foo
	{
		public static void Pack() 
		{
		}
	}

	public class Bar : Foo
	{
		public static void Pack()
		{
		}
	}


	public class Test
	{
		public Test()
		{
			Bar.Pack();
		}
	}
}

This gives me a compiler warning (only a warning!):

The keyword new is required on 'InheritStaticsExample.Bar.Pack()' because it hides inherited member 'InheritStaticsExample.Foo.Pack()'

But Pack() is not an inherited member. And I would think a message saying "new is required" would be an error. I mean, it says its required, but I omitted it. The code compiles just fine into a call to Bar.Pack().

And K. Scott Allen has a great article on Statics at MSDN.

No Comments