Getting the name of current function


Useful snippet for debugging: A function that prints the name of the current function. To be accurate, it prints the name of the calling function.


In C# this is called “reflection”.


In python, it is called “introspection”.


C# example

// —————————————-

using System;

namespace ConsoleApplication1
{
public class ReflectionUtil
{
public static string get_current_method_name()
{
System.Diagnostics.StackFrame stackframe =
new System.Diagnostics.StackFrame(1, true);

return stackframe.GetMethod().ReflectedType.Name
+ “.”
+ stackframe.GetMethod().Name ;
}
}

class Program
{
static void Main(string[] args)
{
System.Console.WriteLine(“Program.Main(): My name is: {0}”, ReflectionUtil.get_current_method_name());
System.Console.ReadLine();
}
}
}
// —————————————-


Python Example:

# —————————————-
# get name of the function
#
# The inspect module lets you examine the call stack.
# From that one can determine the name of the caller
# or the name of the current function
#

import inspect

def get_my_name() :
return inspect.stack()[1][3]

def foo() :
name = get_my_name()
print “foo(): My name is:” , name

class bar :

def beer( self ) :
name = get_my_name()
print “bar.beer(): My name is:” , name

foo()
b = bar()
b.beer()

#—————————————-


C++


This is the Visual Studio 2005 example …

// ————————-

#include “stdafx.h”

#include <iostream>

 

using namespace std;

 

void foo()

{

cout<< __FUNCTION__ << endl;

}

 

int _tmain(int argc, _TCHAR* argv[])

{

   foo();

   return 0;

}


// ——————————-

 


I learned this by reading this article on DevX:



 


Saveen Reddy
2005-10-08 (updated on 2006-06-26)


Comments (0)