Thursday, July 20, 2006

 

Foible #1

I've come across an irritating little foible in C#, and I keep wondering whether it's me not thinking of the right solution, or it's a weakness of C# or .NET. Unfortunately, it's going to take a while to explain.

The short version is: You can't have a static abstract member.

The long version is...

I have written an extensible component. You add functionality (plug-ins) to it by writing additional assemblies and 'registering' them with the component.

The plug-ins must inherit from a public abstract class and I need them to implement their own version of a static property - we'll call it DataFormat.

I would like to implement it like this:

public abstract class MyBaseClass
{
    public static abstract string DataFormat { get; }

    // other stuff
}

But I can't! C# doesn't allow a member to be both abstract and static. So, I must remove one of those modifiers and keep the other, in order to compile.

If I keep the static modifier, i.e.

public abstract class MyBaseClass
{
    public static string DataFormat

    {
        get
        {
            return "";
        }
    }
}

... then I cannot ensure that the inheriting object implements its own version.

If I keep the abstract modifier, i.e.

public abstract class MyBaseClass
{
    public abstract string DataFormat { get; }
}


... then I need to create an instance of the object just to read a static value.

I originally took the first option, but it was painful. The reflection code was more complex and there was no early binding - you had to check at run-time that the object was written with a correct implementation of DataFormat.

So today I relented, and refactored to the second way. There's a lot less code, and it's strongly typed. I just have to instantiate the plug-in class when I need to read the DataFormat value.

This feels wrong, and yet I can't think of a better approach. Oh, and don't think Interfaces help, because they can't have static members.

Comments:
I know that this was a long time ago, but couldn't help but notice your problem.

Looks like a great place to use metadata and attributed and attach these to your class. Then you don't need to instantiate it and everything you need to know about the plugin can be gathered through reflection.
 
Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?