getting the class &/or method names of the invoking object/class RRS feed

  • Question




    When in a method i would like to code something saying which class and method is calling the current method.


    One way to do this, is via System.Diagnostics.StackFrame class.


    MSDN says of this class:

    "StackFrame information will be most informative with Debug build configurations"


    Besides for the above comment, MSDN is thin on the differences this class exhibits between release and debug modes.

    There might be a release mode way to get the info, perhaps using a class from the System.Reflection library.


    Something to do the below, but instead from the System.Reflections namespace.


    System.Diagnostics.StackFrame sf = new StackFrame(1,false);

    MethodBase methodBase = sf.GetMethod();

    Console.WriteLine("Class of invoking method: " + methodBase.DeclaringType);

    Console.WriteLine("Invoking method name: " + methodBase.Name);


    Tried looking myself in the System.Reflection namespace, but didnt see anything there (though something similiar could be expected there).






    Thursday, April 17, 2008 7:29 PM


  • You're already in the reflection namespace when using MethodBase.


    Reflection isn't meant to retrieve the calling method:


    Reflection provides objects (of type Type) that encapsulate assemblies, modules and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.


    You were correct in using the StackFrame to retrieve the method. Although you will be missing information (such as line number) in a release configuration, you still get the calling method:


    A StackFrame is created and pushed on the call stack for every function call made during the execution of a thread. The stack frame always includes MethodBase information, and optionally includes file name, line number, and column number information.

    Thursday, April 17, 2008 8:06 PM