Search code examples
c#-4.0custom-attributes

C# Attribute To Auto Run Method


I'm not sure if this is completely possible. But what I would like to do is create an attribute that when I call a run method then all methods that have a particular run attribute are then ran. I realize this can be done with delegates but I feel it might be a little cleaner looking if it can be achieved with an attribute. I should note that the run order is not important.

Basic design:

//This is the method called that should start off the attribute chain
public void Run(){
  //calling logic in here
}

[AutomatedRun]
private void Method1(){

}

[AutomatedRun]
private void Method2(){

}

Solution

  • Attributes are just metadata. They are useless unless you look for them and perform action. So in this case you need to get those methods that has AutomatedRun attribute using Reflection and call them:

    var methods = typeof(YourClass)
         .GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
         .Where(mi => Attribute.IsDefined(mi, typeof(AutomatedRunAttribute)));
    
    foreach(var m in methods)
        m.Invoke(yourInstance);