Find methods that have custom attribute using reflection

C#ReflectionCustom Attributes

C# Problem Overview


I have a custom attribute:

public class MenuItemAttribute : Attribute
{
}

and a class with a few methods:

public class HelloWorld
{
    [MenuItemAttribute]
    public void Shout()
    {
    }

    [MenuItemAttribute]
    public void Cry()
    {
    }

    public void RunLikeHell()
    {
    }
}

How can I get only the methods that are decorated with the custom attribute?

So far, I have this:

string assemblyName = fileInfo.FullName;
byte[] assemblyBytes = File.ReadAllBytes(assemblyName);
Assembly assembly = Assembly.Load(assemblyBytes);

foreach (Type type in assembly.GetTypes())
{
     System.Attribute[] attributes = System.Attribute.GetCustomAttributes(type);

     foreach (Attribute attribute in attributes)
     {
         if (attribute is MenuItemAttribute)
         {
             //Get me the method info
             //MethodInfo[] methods = attribute.GetType().GetMethods();
         }
     }
}

What I need now is to get the method name, the return type, as well as the parameters it accepts.

C# Solutions


Solution 1 - C#

Your code is completely wrong.
You are looping through every type that has the attribute, which will not find any types.

You need to loop through every method on every type and check whether it has your attribute.

For example:

var methods = assembly.GetTypes()
                      .SelectMany(t => t.GetMethods())
                      .Where(m => m.GetCustomAttributes(typeof(MenuItemAttribute), false).Length > 0)
                      .ToArray();

Solution 2 - C#

Dictionary<string, MethodInfo> methods = assembly
    .GetTypes()
    .SelectMany(x => x.GetMethods())
    .Where(y => y.GetCustomAttributes().OfType<MethodAttribute>().Any())
    .ToDictionary(z => z.Name);

Solution 3 - C#

var classType = new ClassNAME();
var methods = classType.GetType().GetMethods().Where(m=>m.GetCustomAttributes(typeof(MyAttribute), false).Length > 0)
.ToArray();

Now you have all methods with this attribute MyAttribute in class classNAME. You can invoke it anywhere.

public class ClassNAME
{
    [MyAttribute]
    public void Method1(){}

    [MyAttribute]
    public void Method2(){}

    public void Method3(){}
}

class MyAttribute: Attribute { }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionstoicView Question on Stackoverflow
Solution 1 - C#SLaksView Answer on Stackoverflow
Solution 2 - C#JordanBeanView Answer on Stackoverflow
Solution 3 - C#Unknown ArtistView Answer on Stackoverflow