1

I have a method. I want to check a condition and if result of my condition is true throw new exception. I need to name of method for message exception. For example :

public void MyMethod(Notifier not)
{ 
    if(not.HasValue())
        throw new Exception("MyMethod_name : " + not.Value);
} 

How get name of method in the method?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Ehsan
  • 3,431
  • 8
  • 50
  • 70
  • 2
    possible duplicate of [Get Calling function name from Called function in C#](http://stackoverflow.com/questions/1310145/get-calling-function-name-from-called-function-in-c-sharp) – Alexei Levenkov Mar 11 '12 at 05:03
  • see also http://stackoverflow.com/questions/44153/can-you-use-reflection-to-find-the-name-of-the-currently-executing-method – kmote Mar 11 '12 at 05:36
  • if you are using .net 4.5 beta +, you can use [CallerInformation API](http://msdn.microsoft.com/en-us/library/hh534540%28v=vs.110%29.aspx). – Rohit Sharma Mar 11 '12 at 07:16

4 Answers4

2

Is this what you looking for?

new StackFrame(1, true).GetMethod().Name

but again playing with stack means performance hit if misused.

OR are you looking for this - http://www.csharp-examples.net/get-method-names/

OR http://heifner.blogspot.co.nz/2006/12/logging-method-name-in-c.html

OR have a look here nice notes - Get Calling function name from Called function

Hope this helps, cheers!

Community
  • 1
  • 1
Tats_innit
  • 33,991
  • 10
  • 71
  • 77
1

This approach avoids the stack issues:

public void MyMethod(Notifier not)
{ 
    if(not.HasValue())
    {
        string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
        throw new Exception(methodName + ": " + not.Value);
    }
} 

[But note that there may occasionally be unexpected results: for example, small methods or properties are often inlined in release builds, in which case the result will be the caller's method name instead.]

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
kmote
  • 16,095
  • 11
  • 68
  • 91
0
public void MyMethod(Notifier not)
{ 
  StackFrame stackFrame = new StackFrame();
  MethodBase methodBase = stackFrame.GetMethod();

  if(not.HasValue())
      throw new Exception("MyMethod_name : " + methodBase.Name);
}   
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Ritch Melton
  • 11,498
  • 4
  • 41
  • 54
0

Using Reflection you can get the method name.....By using the powerful reflection facilities in the framework, you can invoke the method. This involves the System.Reflection namespace and theGetMethod method.

For implementation of Reflection, take a reference to this link......

http://www.dotnetperls.com/getmethod