Virtual Static Interface Methods in C# – Introduction

For quite some time now I wanted to blog about a feature I missed in C# for a long time, what I used to call static interfaces or static class interfaces.

In a class definition you can always add static properties and methods. In my opinion, these static elements really are elements of  a separate class which acts as a “StaticClass” for the original class. For example, a framework might need to operate on static methods defined by such “StaticClasses” depending on the type of a parameter passed to the framework.

Pseudo Code:

static interface IStaticClass
{
    void DoSomething();
}
class Foo : IStaticClass
{
    public static virtual void DoSomething()
    {
        Console.WriteLine("hello from Foo");
    }
}
class Bar : IStaticClass
{
    public static virtual void DoSomething()
    {
        Console.WriteLine("hello from Bar");
    }
}
class FooEx : Foo
{
    public static override void DoSomething()
    {
        Console.WriteLine("hello from FooEx");
    }
}
void Main()
{
    Bar bar = new Bar();
    Foo foo = new FooEx();

    // magic happens here:
    (bar.GetType() as IStaticClass).DoSomething();
    foo.class.DoSomething();
}

Of course I know that this is not possible in C#, and my personal impression is now that such a solution (or the desire to have such a solution) would clearly be an indication of bad design.

One reason for this indication is that there is a fundamental difference between virtual methods and static methods:

Static methods are statically identified by Namespace + Class name + Method name + Parameter types.

Virtual methods are dynamically identified by Method name + Parameter types of the Virtual Method Table of the Class definition (Namespace + Class name), optionally implementing an Interface definition (Namespace + Interface name), of an instantiated object.

I am not alone, though. A quick search on StackOverflow to research for these blogs came up with a quite a lot of questions:

The next two blogs illustrate a solution using techniques already available in C#.

One Response to Virtual Static Interface Methods in C# – Introduction

  1. […] sketched the question of “virtual static interface methods” in my previous […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: