Alex Rivera | Logout

Interfaces or Attributes for Tagging Classes?

Asked 2010-01-14T11:55:37.060
20

I have a couple of classes that I wish to tag with a particular attribute. I have two approaches in mind. One involves using an Attribute-extending class. The other uses an empty interface:

Attributes

public class FoodAttribute : Attribute { }

[Food]
public class Pizza { /* ... */ }

[Food]
public class Pancake { /* ... */ }

if (obj.IsDefined(typeof(FoodAttribute), false)) { /* ... */ }

Interface

public interface IFoodTag { }

public class Pizza : IFoodTag { /* ... */ }
public class Pancake : IFoodTag { /* ... */ }

if (obj is IFoodTag) { /* ... */ }

I'm hesitant to use the attributes due to its usage of Reflection. At the same time, however, I'm hesitant on creating an empty interface that is only really serving as a tag. I've stress-tested both and the time difference between the two is only about three milliseconds, so performance is not at stake here.

Edit
Report

1 Answer

18

Well, with attributes, you can always create the attribute in such a way that its function doesn't propagate to descendant types automatically.

With interfaces, that's not possible.

I would go with attributes.

answered 2010-01-14T11:57:41.870

Your Answer