How can I find the full name of a calling method in C#? I have seen solutions:
How I can get the calling methods in C#
How can I find the method that called the current method?
Get Calling function name from Called function
But they only give me the top level. Consider the example:
namespace Sandbox { class Program { static void Main(string[] args) { test(); } static void test() { var stackTrace = new StackTrace(); var methodBase = stackTrace.GetFrame(1).GetMethod(); Console.WriteLine(methodBase.Name); } } }
This simply outputs 'Main'. How can I get it to print 'Sandbox.Program.Main'?
It's for a simple logging framework that I am working on.
Adding onto Matzi's Answer:
Here is the solution:
namespace Sandbox { class Program { static void Main(string[] args) { test(); } static void test() { var stackTrace = new StackTrace(); var methodBase = stackTrace.GetFrame(1).GetMethod(); var Class = methodBase.ReflectedType; var Namespace = Class.Namespace; // Added finding the namespace Console.WriteLine(Namespace + "." + Class.Name + "." + methodBase.Name); } } }
It produces 'Sandbox.Program.Main' like it should.
Function Calling: A function call is an important part of the C programming language. It is called inside a program whenever it is required to call a function. It is only called by its name in the main() function of a program. We can pass the parameters to a function calling in the main() function.
When one piece of code invokes or calls a function, it is done by the following syntax: variable = function_name ( args, ...); The function name must match exactly the name of the function in the function prototype. The args are a list of values (or variables containing values) that are "passed" into the function.
Calling a function inside of itself is called recursion.
This is something like here.
MethodBase method = stackTrace.GetFrame(1).GetMethod(); string methodName = method.Name; string className = method.ReflectedType.Name; Console.WriteLine(className + "." + methodName);
I think the best way to get the full name is:
this.GetType().FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name;
Or try this:
string method = string.Format("{0}.{1}", MethodBase.GetCurrentMethod().DeclaringType.FullName, MethodBase.GetCurrentMethod().Name);
And if you want to display the most recent function call, you can use:
StackTrace st = new StackTrace(); StackFrame sf = st.GetFrame(0); var methodName = sf.GetMethod();
But if you want to display the tree of calling functions, you can do it like this:
if (st.FrameCount >1) { // Display the highest-level function call // in the trace. StackFrame sf = st.GetFrame(st.FrameCount-1); Console.WriteLine(" Original function call at top of call stack):"); Console.WriteLine(" {0}", sf.GetMethod()); }
For more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With