1

I'm looking for something like this:

public void MyCallingMethod()
        {
           var myObj = new Obj(Context.Method.Name);
        }

Or even better....

Would it be possible to determine from myObj what calling method lead to the creation of the object, but this would have to be reliable, because I will be using it for reporting.

Expected result would be "MyCallingMethod" or "MyCallingMethod()" as a string.

halfer
  • 19,824
  • 17
  • 99
  • 186
JL.
  • 78,954
  • 126
  • 311
  • 459

2 Answers2

2

You could look at GetCurrentMethod

MethodBase method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = method.Name;
string className = method.ReflectedType.Name;

string fullMethodName = className + "." + methodName;

But i assume that using that kind of ,,thing'' is not good solution for anything. I think you have misarchitected you app

Ji Ra
  • 3,187
  • 1
  • 12
  • 17
  • 1
    Please dont use relfection. There are better ways now http://stackoverflow.com/a/13496108/1789202 – CSharpie Jul 06 '15 at 10:37
1

You could try the .NET 4.5 CallerMemberName attribute:

public Obj([CallerMemberName]string caller = null)
{ }

If you call this method like this:

public void MyCallingMethod()
{
    new Obj();
}

Then the value of caller will be the string "MyCallingMethod".

ForNeVeR
  • 6,726
  • 5
  • 24
  • 43