Wednesday, February 13, 2013

Virtual Static


In Smalltalk a Class is a first level object just like everything else in the system. Objects get instantiated using the Class as a template but the Class itself can have its own properties and methods. In fact constructors are just class methods in Smalltalk that return an instance.

Now as a C# programmer I've always thought of static properties and methods as the same thing as Smalltalk's class properties and methods. In the back of my head I knew that C# didn't have first-level Class objects but the static paradigm seemed to fit. So when the other day I wanted to override a static method in a subclass I figured no problem just mark the one in the superclass 'virtual' and then add my new implementation. One problem was that compiler balked at 'virtual static'.

After some searching around I found this blog post explaining why this was not a valid combination of keywords. As Eric Libbert writes:
Related questions come up frequently, in various forms. Usually people phrase it by asking me why C# does not support “virtual static” methods. I am always at a loss to understand what they could possibly mean, since “virtual” and “static” are opposites! “virtual” means “determine the method to be called based on run time type information”, and “static” means “determine the method to be called solely based on compile time static analysis”.
Turns out 'static' is really not equal to 'class'. I must admit I almost shed a tear that day as this sunk in.