Reputation: 59
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;
}
Upvotes: 1
Views: 1228
Reputation: 499092
.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;
}
Upvotes: 4