0

I have a classes called BillingActivity, DevelopmentActivity, ResearchActivity all implementing IActivity.

Somewhere in my app I enumerate a dll containing all types. Check wether typeof(IActivity).IsAssignable(type) if so I want to get string typeDescription = type.Attribute.Value or similar what I want is to put a attribute on a class OR on the above classes (depends what suggestions you make or what solutions are possible) like

[ActivityType = "Billing"].
public class BillingActivity {}

I do not want to get a instance of that type I just want to get the description(attribute `s value).

How can I do that? Can someone push me in the right direction please?

Elisabeth
  • 20,496
  • 52
  • 200
  • 321

2 Answers2

1

Create a custom attribute with a single string property, tag your classes with it, then GetCustomAttributes to test a particular class is tagged with the attribute, and if it is you can read the property to pull the name you set.

public class ActivityTypeAttribute : Attribute 
{
 public Name { get; set; }
}

[ActivityType(Name="MyClass")]
public class MyClass { }

...
{
 ActivityTypeAttribute att = (ActivityTypeAttribute)Attribute.GetCustomAttribute(typeof(MyClass), typeof(ActivityTypeAttribute));

  Debug.Assert( att.Name == "MyClass" );
}
...

Edit - Also, please read this

What's the simplest most elegant way to utilize a custom attribute

Community
  • 1
  • 1
asawyer
  • 17,642
  • 8
  • 59
  • 87
  • When I write this [ActivityType(Name="MyClass")] over MyClass it can not be resolved? Shouldn`t MyClass inherit from Attribute? – Elisabeth Oct 01 '10 at 13:37
  • No, the custom attribute class is the only one who needs to inherit from Attribute. Can you post an example of what your seeing? – asawyer Oct 01 '10 at 13:41
0
ActivityType result =
  (ActivityType)Attribute.GetCustomAttribute(this.GetType(), typeof(ActivityType));
Brad
  • 15,361
  • 6
  • 36
  • 57