Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding all classes with a particular attribute

I've got a .NET library in which I need to find all the classes which have a custom attribute I've defined on them, and I want to be able to find them on-the-fly when an application is using my library (ie - I don't want a config file somewhere which I state the assembly to look in and/ or the class names).

I was looking at AppDomain.CurrentDomain but I'm not overly familiar with it and not sure how elivated the privlages need to be (I want to be able to run the library in a Web App with minimal trust if possible, but the lower the trust the happier I'd be). I also want to keep performance in mind (it's a .NET 3.5 library so LINQ is completely valid!).

So is AppDomain.CurrentDomain my best/ only option and then just looping through all the assemblies, and then types in those assemblies? Or is there another way

like image 397
Aaron Powell Avatar asked Apr 06 '09 03:04

Aaron Powell


People also ask

How to get attribute value in c#?

First, declare an instance of the attribute you want to retrieve. Then, use the Attribute. GetCustomAttribute method to initialize the new attribute to the value of the attribute you want to retrieve. Once the new attribute is initialized, you simply use its properties to get the values.

What is an attribute C#?

Advertisements. An attribute is a declarative tag that is used to convey information to runtime about the behaviors of various elements like classes, methods, structures, enumerators, assemblies etc. in your program. You can add declarative information to a program by using an attribute.

How would you determine if a class has a particular attribute?

The same you would normally check for an attribute on a class. Here's some sample code. typeof(ScheduleController) . IsDefined(typeof(SubControllerActionToViewDataAttribute), false);


1 Answers

IEnumerable<Type> GetTypesWith<TAttribute>(bool inherit)                                where TAttribute: System.Attribute  { return from a in AppDomain.CurrentDomain.GetAssemblies()           from t in a.GetTypes()           where t.IsDefined(typeof(TAttribute),inherit)           select t;  } 
like image 178
Mark Cidade Avatar answered Oct 02 '22 12:10

Mark Cidade