Hayden
Hayden

Reputation:

Can I find out if a particular attribute was present on the calling function?

Is there a way to find out if the calling function had attributes set on it?

[RunOnPlatformB]
int blah()
{
    return boo();
}

int boo()
{
    // can i find out if RunOnPlatformB was set on my caller?
}

Upvotes: 1

Views: 155

Answers (2)

Shalom Craimer
Shalom Craimer

Reputation: 21449

You can get the caller function from the stack trace, and query its attributes:

System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace();
Object[] attr =
   st.GetFrame(1).GetMethod().GetCustomAttributes(typeof(RunOnPlatformBAttribute), false);
if (attr.Length > 0) {
   // Yes, it does have the attribute RunOnPlatformB
}

Upvotes: 1

MrTelly
MrTelly

Reputation: 14865

First off you have to go up the StackFrame to find what called you, in my experience this is a horribly expensive operation, and may have security probs as well depending on the context you're running as. The code will be something like this -

using System.Diagnostics;
using System.Reflection;

....
    StackTrace stackTrace = new StackTrace();           
    StackFrame[] stackFrames = stackTrace.GetFrames(); 

    StackFrame caller = stackFrames[1]; 

    MethodInfo methodInfo = caller.GetMethod() as MethodInfo;
    foreach (Attribute attr in methodInfo.GetCustomAttributes())
    .....

Upvotes: 0

Related Questions