0

I'm looking at a solution for getting the class name of a calling method in .Net 4.5 and I'm hoping to use a custom property attribute to implement it. Here is an example of using the System attribute CallerMemberName to get the member name but for my own attribute I'm not sure which functions to implement to return a value.

Does anyone know of links to more documentation on implementing this type of attribute or of any examples?

So far I'm planning on using the following:

[AttributeUsage(AttributeTargets.Parameter)]
class MyAttribute : Attribute
{
    //some method to implement returning the attribute value
}

class CallerTestClass
{
    public string GetCallerClass(
        [MyAttribute]string className = "")
    {
        return className;
    }
}
Community
  • 1
  • 1
ars265
  • 1,949
  • 3
  • 21
  • 37

1 Answers1

3

You can't, basically. The C# compiler has special knowledge of the CallerMemberName attribute - it doesn't have special knowledge of your attribute.

It sounds like you should just be able to use CallerMemberName though, rather than having your own attribute at all...

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Well I need the calling class, not calling method. There is a way to get the assembly information using CallerFilePath but I was hoping I could do it more efficient than parsing the assembly for the class information each time the method is called – ars265 Dec 03 '15 at 18:03
  • @ars265: No, there isn't. And of course the file may not match the class name. – Jon Skeet Dec 03 '15 at 18:51