views:

466

answers:

2

When employing custom attributes to store meta-data, is it best to decorate the interface, or the class that implements the interface, assuming that any class that implements the interface would have the same data in the attribute?

Update: Basically i'm writing a custom data storage mechanism for a project, and the objects represent the various tables being stored. The custom attribute is used to designate which table in the dataset is used to store the objects of that class, and also to identify which tables are involved in a n:m relationship.

So if i put the attributes on the interface, is this a clearer approach, or does it clutter the interface and make accessing the data itself more cumbersome?

+2  A: 

It depends on the scenario. WCF, for example, decorates interfaces for the operation contracts.

However, if you are going to be talking about objects (rather than the interface itself), note that it can be painful for calling code to get hold of interface metadata, especially if the class uses explicit interface implementation.

It would be more common to decorate the class, but that isn't quite the same question ;-p

If the attribute really is specific to the interface (not the instances), then fine - decorate the interface and talk about typeof(IFoo) etc. But if you expect code to be able to set per-type values for the attributes, it will have to be at the class level.

What is the scenario?

Marc Gravell
+2  A: 

Well it depends on whether or not the interface has anything to do with the metadata.

interface IRunnable
{
    void Run();
}

class Test : IRunnable
{
    public void Run() { }
}

In this example it would make sense to put the attributes on the interface if they pertain to the intent of the interface. If the attributes are applicable across all implementations then put the attributes on the interface.

However if the attributes have nothing to do with the "runnability" (with "runnability" pertaining to IRunnable not the CLR) of the class then put the attributes on the class.

Andrew Hare