]> Late static binding in C# - virtual static 🌐:aligrant.com

Late static binding in C# - virtual static

Alastair Grant | Mon 23 May 2016

In PHP there is a really handy concept called late static binding. You can run a piece of code such as static::MyMethod() and it will execute the method "MyMethod" as defined in the implemented class. This means you can have a default MyMethod() implementation in an abstract class and a different one in a child class.

I hit a requirement for similar functionality today in C# - we have child classes that define particular implementations of an abstract dataset. This is fine and we process this using Generics. But then an issue came out that we need to physically load the data differently for one implementation. As each class instance represents a record and not the whole implementation we need a static method that may or may not have to do custom processing.

Our nice Generics are now out of the window, as we have to run specific code for different implementations, and know when and where to run each one.

Fortunately, you can hack around this a bit using slow, but handy, reflection.

public class Processor where T : BaseClass, new() {
  public static void DoSomething() {
    System.Reflection.MethodInfo mi = typeof(T).GetMethod("MyStatic");
    if(mi != null) mi.Invoke(null, new object[] {}); else BaseClass.MyStatic(); }
  }
}

The "MyStatic" static method is defined in the BaseClass, but if blocked with the "new" keyword and reimplemented in a child implementation of BaseClass it is found via reflection and executed instead.

It's not as elegant as PHP but cracks the problem.

Breaking from the voyeuristic norms of the Internet, any comments can be made in private by contacting me.

Related