Search code examples
c#reflectionattributesmethodinfo

How would I use reflection to call all the methods that has a certain custom attribute?


I have a class with a bunch of methods.

some of these methods are marked by a custom attribute.

I would like to call all these methods at once.

How would I go about using reflection to find a list of all the methods in that class that contains this attribute?


Solution

  • Once you get the list of methods, you would cycle query for the custom attributes using the GetCustomAttributes method. You may need to change the BindingFlags to suit your situation.

    var methods = typeof( MyClass ).GetMethods( BindingFlags.Public );
    
    foreach(var method in methods)
    {
        var attributes = method.GetCustomAttributes( typeof( MyAttribute ), true );
        if (attributes != null && attributes.Length > 0)
            //method has attribute.
    
    }