1

Is it possible to get the name of the calling method, and execute code based on those results?

Below, I have two methods that are used for database CRUD operations. One adds an object to the database, another updates. Both return an object which contains a stat report for an operation.

Under certain conditions, I wouldn't bother updating the pkey field for an operation stat object within the Update method, if it's returning the stat-obj to the Add method.

public OperationStat Add(object obj)
{
  // Contains operation status data.
  OperationStat op = new OperationStat();
  op.PrimaryKey = pkey.newkey();

  // Record to update
  Person pete = new Person();

  // call update method.
  op = this.Update(pete);
}

public OperationStat Update(object obj)
{
  OperationStat op = new OperationStat();
  string callmethod = "Add";

  // Get stacktrace.
  StackTrace stackTrace = new StackTrace();
  StackFrame stackFrame = stackTrace.GetFrame(1);
  MethodBase methodBase = stackFrame.GetMethod();

  if(methodBase.Name != callmethod)
  {
   // create new primary key for status.
   op.Primarykey = pkey.newkey();
  }

  // fill operation stat object with details
  return op;
}
Praxeolitic
  • 22,455
  • 16
  • 75
  • 126
Klue
  • 59
  • 7
  • 1
    You shouldn't rely on the stack trace, as the caller may perfectly be optimized [out of the stack](http://stackoverflow.com/a/6597522/276994). – Vlad Jun 08 '13 at 14:34
  • 1
    Reading your code, I am wondering why you don't pass "Add" as an argument of Update()... – Alexandre Vinçon Jun 08 '13 at 14:35

1 Answers1

4

.NET 4.5 introduces a few new attributes that give you this kind of information.

The CallerMethodNameAttribute:

Allows you to obtain the method or property name of the caller to the method.


public OperationStat Update(object obj, [CallerMethodName] string calledFrom = "")
{
  OperationStat op = new OperationStat();
  string callmethod = "Add";

  if(calledFrom != callmethod)
  {
    op.Primarykey = pkey.newkey();
  }

  return op;
}
Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • Any solution for .Net 4.0 environment? – Klue Jun 08 '13 at 14:48
  • My study of stack traces/frames leads me to believe issues could arise where the calling method name isn't available or the incorrect name is received: (optimization, native methods?). – Klue Jun 08 '13 at 14:55
  • @Klue - Unfortunately, there are no other options in prior versions. You may want to look at the [`MethodImplAttribute`](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.methodimplattribute.aspx) and the [`MethodImplOptions`](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.methodimploptions%28v=VS.110%29.aspx) enumeration. – Oded Jun 08 '13 at 14:59