0

I would like to decorate a number of functions with a custom attribute. These functions will not return a specific type and can really return any type.

Now this function will call any number of other functions, and then at some point in the operation I would like to know "what is the text/value last custom attribute in the call stack".

How can I do this?

Example:

[CustomAttribute("Hello World...")]
public void SomeFunction
{
    return Func1("myparam")
}

public void Func1(string xx)
{
    return Func2(xx)
}

public string Func2(string yy)
{
    //I would like to know what is the value\text of the attribute "CustomAttribute".
    //If there are multiples in the call stack, return the last one (which might be in another class and project as Func2)
}
Cameron Castillo
  • 2,712
  • 10
  • 47
  • 77
  • 1
    Dealing with custom attributes at runtime usually involves `System.Reflection` APIs. I'd suggest starting by writing code to get the `CustomAttribute` value of a specific hard-coded method you know about. Then, you can modify that code to search an instance of the `System.Diagnostics.StackTrace` class. – Joe Sewell Apr 20 '20 at 15:07

1 Answers1

2

As mentioned by @joe Sewell, the overall approach would be to iterate over the stackTrace and check each method if it has the attribute. Combining Read the value of an attribute of a method with Get stack trace gives the following result:

Here is an example on how to do it:

[System.AttributeUsage(System.AttributeTargets.Method)]
public class MyAttribute : Attribute
{
    public string Value { get; }

    public MyAttribute(string value)
    {
        Value = value;
    }

    public static string GetValueOfFirstInStackTrace()
    {
        StackTrace stackTrace = new StackTrace();           
        StackFrame[] stackFrames = stackTrace.GetFrames(); 

        foreach (var stackFrame in stackFrames)
        {
            var method = stackFrame.GetMethod();
            MyAttribute attr = (MyAttribute)method.GetCustomAttributes(typeof(MyAttribute), true).FirstOrDefault();
            if (attr != null)
            {
                string value = attr.Value;  
                return value;
            }
        }

        return null;
    }
}
JonasH
  • 28,608
  • 2
  • 10
  • 23