Question

C#, implement 'static abstract' like methods

I recently ran into a problem where it seems I need a 'static abstract' method. I know why it is impossible, but how can I work around this limitation?

For example I have an abstract class which has a description string. Since this string is common for all instances, it is marked as static, but I want to require that all classes derived from this class provide their own Description property so I marked it as abstract:

abstract class AbstractBase
{
    ...
    public static abstract string Description{get;}
    ...
}

It won't compile of course. I thought of using interfaces but interfaces may not contain static method signatures.

Should I make it simply non-static, and always get an instance to get that class specific information?

Any ideas?

 45  47467  45
1 Jan 1970

Solution

 34

You can't.

The place to do this is with Attributes.

Eg

[Name("FooClass")]
class Foo
{
}
2009-05-05

Solution

 8

If you don't mind deferring to implementations to sensibly implement the Description property, you can simply do

public abstract string ClassDescription {get; } 
// ClassDescription is more intention-revealing than Description

And implementing classes would do something like this:

static string classDescription="My Description for this class";
override string  ClassDescription { get { return classDescription; } }

Then, your classes are required to follow the contract of having a description, but you leave it to them to do it sensibly. There's no way of specifying an implementation in an object-oriented fashion (except through cruel, fragile hacks).

However, in my mind this Description is class metadata, so I would prefer to use the attribute mechanism as others have described. If you are particularly worried about multiple uses of reflection, create an object which reflects over the attribute that you're concerned with, and store a dictionary between the Type and the Description. That will minimize the reflection (other than run time type inspection, which isn't all that bad). The dictionary can be stored as a member of whatever class that typically needs this information, or, if clients across the domain require it, via a singleton or context object.

2009-05-11