Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection - Access custom attributes by name

Tags:

c#

reflection

I'm attempting to see if a given method is decorated with an attribute, (the attribute in question is NUnit.Framework.TestAttribute) but I need to be able to check for the attribute regardless of what version the attribute is. Currently, I have nunit.framework.dll version 2.6.2 in the project using reflection, and version 2.6.0 of the dll in the test. The reflection is not finding the attribute.

Is there some way to do

bool isTest = method.GetCustomAttributes(typeof(TestAttribute), true).Length > 0;

without having access to the correct version of the TestAttribute dll?

where method is of type MethodInfo.

like image 951
Luke Willis Avatar asked Jul 15 '26 13:07

Luke Willis


1 Answers

You can get all attributes and filter by name:

method.GetCustomAttributes(true)
      .Where(a => a.GetType().FullName == "NUnit.Framework.TestAttribute");
like image 85
Thomas Levesque Avatar answered Jul 18 '26 18:07

Thomas Levesque