0

I want to be able to add some code to the beginning of a method if it has a certain attribute. For example, I want it to return immediately if it has a particular attribute and it is Wednesday:

[Return()]
public void MyMethod()
{
    //If [Return()] attribute and its Wednesday, it returns and never "Does Stuff"
    //Do Stuff
}

I have the start to my Attribute, but I cannot figure out how to run the code ahead of the method.

[AttributeUsage(AttributeTargets.Method)]
public class ReturnAttribute : Attribute
{
     public void Return()
     {
         if(Today == Wednesday)
         {
             return;
         }
     {   
}

I know the ReturnAttribute is incorrect. I posted that code to show how close (or far) I have come.

How can I insert code at the beginning of a method, if that method is marked with the specified attribute?

Evorlor
  • 7,263
  • 17
  • 70
  • 141
  • You may want to look at the Fody libraries and see how they work – BradleyDotNET Jan 18 '17 at 19:49
  • You would have to add code to every method that added ```[Return]``` to use reflection to find the attribute, instatiate it and then run it. It would be far simpler to just add a one-line helper method that returned a ```bool``` to the top of the method and return if it's true. ``` public void Blah() { if (Helper.IsItWednesday()) { return; } } ``` – Martin Costello Jan 18 '17 at 20:09
  • This technique is all about method interception. Please take a look at this question: http://stackoverflow.com/questions/25366243/intercept-method-calls. Take a close look at the second answer and imagine the line `_stopWatch = Stopwatch.StartNew();` being replaced by "if day not is Wednesday" – Peter Bons Jan 18 '17 at 20:17

1 Answers1

0

Compile time solution

Perhaps you could try using ConditionalAttribute, and set a condition that is never true. For example....

[Conditional("NEVER")]
public static void MyMethod(int x)
{
    //This code will never run
}

This will have the effect you want, but only at compile time. Note that this will only work on methods that return void. Not sure what you'd want to do with methods that return something else, since you don't want any code to run, and therefore cannot instantiate any objects to return.

Run time, cut & paste-able solution

Add a bit of reflection to the top of your method:

using System.Reflection;
using System.Linq;

[Return()]
void MyMethod(int x)
{
    var skip = MethodBase.GetCurrentMethod().GetCustomAttributes( typeof( ReturnAttribute ), false ).Any();
    if (skip) return;
    //Rest of the code goes here
}
John Wu
  • 50,556
  • 8
  • 44
  • 80
  • Thank you, but I do not understand how this works (even after reading the linked documentation). I updated my question to be more clear, as I think your answer only tells a method whether or not it compiles. – Evorlor Jan 18 '17 at 20:05
  • Added a second option for run-time check. – John Wu Jan 18 '17 at 20:58