<p>Like the title says: Can reflection give you the name of the currently executing method.</p>

<p>I'm inclined to guess not, because of the Heisenberg problem.  How do you call a method that will tell you the current method without changing what the current method is?  But I'm hoping someone can prove me wrong there.</p>

<p><strong>Update:</strong>  </p>

<ul>
<li>Part 2:  Could this be used to look inside code for a property as well?  </li>
<li>Part 3:  What would the performance be like?</li>
</ul>

<p><strong>Final Result</strong><br>
I learned about MethodBase.GetCurrentMethod().  I also learned that not only can I create a stack trace, I can create only the exact frame I need if I want.  </p>

<p>To use this inside a property, just take a .Substring(4) to remove the 'set_' or 'get_'.</p>

[{'answer_id': 44158, 'author': 'bdukes', 'author_id': 2688, 'author_profile': 'https://Stackoverflow.com/users/2688', 'pm_score': 2, 'selected': False, 'text': '<p>I think you should be able to get that from creating a <a href="http://msdn.microsoft.com/en-us/library/6zh7csxz(VS.80).aspx" rel="nofollow noreferrer">StackTrace</a>.  Or, as @<a href="https://stackoverflow.com/questions/44153/can-you-use-reflection-to-find-the-name-of-the-currently-executing-method#44166">edg</a> and @<a href="https://stackoverflow.com/questions/44153/can-you-use-reflection-to-find-the-name-of-the-currently-executing-method#44170">Lars Mæhlum</a> mention, MethodBase.<a href="http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.getcurrentmethod.aspx" rel="nofollow noreferrer">GetCurrentMethod</a>()</p>\n'}, {'answer_id': 44165, 'author': 'Lex', 'author_id': 4109, 'author_profile': 'https://Stackoverflow.com/users/4109', 'pm_score': 4, 'selected': False, 'text': '<p>Yes definitely.</p>\n\n<p>If you want an object to manipulate I actually use a function like this:</p>\n\n<pre><code>public static T CreateWrapper&lt;T&gt;(Exception innerException, params object[] parameterValues) where T : Exception, new()\n{\n    if (parameterValues == null)\n    {\n        parameterValues = new object[0];\n    }\n\n    Exception exception   = null;\n    StringBuilder builder = new StringBuilder();\n    MethodBase method     = new StackFrame(2).GetMethod();\n    ParameterInfo[] parameters = method.GetParameters();\n    builder.AppendFormat(CultureInfo.InvariantCulture, ExceptionFormat, new object[] { method.DeclaringType.Name, method.Name });\n    if ((parameters.Length &gt; 0) || (parameterValues.Length &gt; 0))\n    {\n        builder.Append(GetParameterList(parameters, parameterValues));\n    }\n\n    exception = (Exception)Activator.CreateInstance(typeof(T), new object[] { builder.ToString(), innerException });\n    return (T)exception;\n}\n</code></pre>\n\n<p>This line:</p>\n\n<pre><code>MethodBase method     = new StackFrame(2).GetMethod();\n</code></pre>\n\n<p>Walks up the stack frame to find the calling method then we use reflection to obtain parameter information values passed to it for a generic error reporting function. To get the current method simply use current stack frame (1) instead.</p>\n\n<p>As others have said for the current methods name you can also use:</p>\n\n<pre><code>MethodBase.GetCurrentMethod()\n</code></pre>\n\n<p>I prefer walking the stack because if look internally at that method it simply creates a StackCrawlMark anyway. Addressing the Stack directly seems clearer to me </p>\n\n<p>Post 4.5 you can now use the [CallerMemberNameAttribute] as part of the method parameters to get a string of the method name - this may help in some scenarios (but really in say the example above)</p>\n\n<pre><code>public void Foo ([CallerMemberName] string methodName = null)\n</code></pre>\n\n<p>This seemed to be mainly a solution for INotifyPropertyChanged support where previously you had strings littered all through your event code.</p>\n'}, {'answer_id': 44166, 'author': 'Ed Guiness', 'author_id': 4200, 'author_profile': 'https://Stackoverflow.com/users/4200', 'pm_score': 8, 'selected': False, 'text': '<p>For non-<code>async</code> methods one can use</p>\n\n<pre><code>System.Reflection.MethodBase.GetCurrentMethod().Name;\n</code></pre>\n\n<p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.reflection.methodbase.getcurrentmethod" rel="noreferrer">https://learn.microsoft.com/en-us/dotnet/api/system.reflection.methodbase.getcurrentmethod</a></p>\n\n<p>Please remember that for <code>async</code> methods it will return "MoveNext".</p>\n'}, {'answer_id': 44170, 'author': 'Lars Mæhlum', 'author_id': 960, 'author_profile': 'https://Stackoverflow.com/users/960', 'pm_score': 4, 'selected': False, 'text': '<p>Try this inside the Main method in an empty console program:</p>\n\n<pre><code>MethodBase method = MethodBase.GetCurrentMethod();\nConsole.WriteLine(method.Name);\n</code></pre>\n\n<p>Console Output:<br>\n<code>Main</code></p>\n'}, {'answer_id': 44171, 'author': 'denis phillips', 'author_id': 748, 'author_profile': 'https://Stackoverflow.com/users/748', 'pm_score': 3, 'selected': False, 'text': "<p>EDIT: MethodBase is probably a better way to just get the method you're in (as opposed to the whole calling stack). I'd still be concerned about inlining however.</p>\n\n<p>You can use a StackTrace within the method:</p>\n\n<pre><code>StackTrace st = new StackTrace(true);\n</code></pre>\n\n<p>And the look at the frames:</p>\n\n<pre><code>// The first frame will be the method you want (However, see caution below)\nst.GetFrames();\n</code></pre>\n\n<p>However, be aware that if the method is inlined, you will not be inside the method you think you are. You can use an attribute to prevent inlining:</p>\n\n<pre><code>[MethodImpl(MethodImplOptions.NoInlining)]\n</code></pre>\n"}, {'answer_id': 44215, 'author': 'Joel Coehoorn', 'author_id': 3043, 'author_profile': 'https://Stackoverflow.com/users/3043', 'pm_score': 6, 'selected': False, 'text': "<p>The snippet provided by Lex was a little long, so I'm pointing out the important part since no one else used the exact same technique:</p>\n\n<pre><code>string MethodName = new StackFrame(0).GetMethod().Name;\n</code></pre>\n\n<p>This should return identical results to the <em>MethodBase.GetCurrentMethod().Name</em> technique, but it's still worth pointing out because I could implement this once in its own method using index 1 for the <em>previous</em> method and call it from a number of different properties.  Also, it only returns one frame rather then the entire stack trace:</p>\n\n<pre><code>private string GetPropertyName()\n{  //.SubString(4) strips the property prefix (get|set) from the name\n    return new StackFrame(1).GetMethod().Name.Substring(4);\n}\n</code></pre>\n\n<p>It's a one-liner, too ;)</p>\n"}, {'answer_id': 172562, 'author': 'jesal', 'author_id': 20092, 'author_profile': 'https://Stackoverflow.com/users/20092', 'pm_score': 2, 'selected': False, 'text': '<p>How about this:</p>\n<pre class="lang-cs prettyprint-override"><code>StackFrame frame = new StackFrame(1);\nframe.GetMethod().Name; //Gets the current method name\n\nMethodBase method = frame.GetMethod();\nmethod.DeclaringType.Name //Gets the current class name\n</code></pre>\n'}, {'answer_id': 15310053, 'author': 'John Nilsson', 'author_id': 24243, 'author_profile': 'https://Stackoverflow.com/users/24243', 'pm_score': 8, 'selected': True, 'text': '<p>As of .NET 4.5, you can also use <a href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callermembernameattribute" rel="noreferrer">[CallerMemberName]</a>.</p>\n<p>Example: a property setter (to answer part 2):</p>\n<pre><code>protected void SetProperty&lt;T&gt;(T value, [CallerMemberName] string property = null)\n{\n    this.propertyValues[property] = value;\n    OnPropertyChanged(property);\n}\n\npublic string SomeProperty\n{\n    set { SetProperty(value); }\n}\n</code></pre>\n<p>The compiler will supply matching string literals at call sites, so there is basically no performance overhead.</p>\n'}, {'answer_id': 21295459, 'author': 'drzaus', 'author_id': 1037948, 'author_profile': 'https://Stackoverflow.com/users/1037948', 'pm_score': 4, 'selected': False, 'text': '<p>Comparing ways to get the method name -- using an <a href="https://gist.github.com/zaus/8055941" rel="noreferrer">arbitrary timing construct</a> in LinqPad:</p>\n\n<h3>CODE</h3>\n\n<pre><code>void Main()\n{\n    // from http://blogs.msdn.com/b/webdevelopertips/archive/2009/06/23/tip-83-did-you-know-you-can-get-the-name-of-the-calling-method-from-the-stack-using-reflection.aspx\n    // and https://stackoverflow.com/questions/2652460/c-sharp-how-to-get-the-name-of-the-current-method-from-code\n\n    var fn = new methods();\n\n    fn.reflection().Dump("reflection");\n    fn.stacktrace().Dump("stacktrace");\n    fn.inlineconstant().Dump("inlineconstant");\n    fn.constant().Dump("constant");\n    fn.expr().Dump("expr");\n    fn.exprmember().Dump("exprmember");\n    fn.callermember().Dump("callermember");\n\n    new Perf {\n        { "reflection", n =&gt; fn.reflection() },\n        { "stacktrace", n =&gt; fn.stacktrace() },\n        { "inlineconstant", n =&gt; fn.inlineconstant() },\n        { "constant", n =&gt; fn.constant() },\n        { "expr", n =&gt; fn.expr() },\n        { "exprmember", n =&gt; fn.exprmember() },\n        { "callermember", n =&gt; fn.callermember() },\n    }.Vs("Method name retrieval");\n}\n\n// Define other methods and classes here\nclass methods {\n    public string reflection() {\n        return System.Reflection.MethodBase.GetCurrentMethod().Name;\n    }\n    public string stacktrace() {\n        return new StackTrace().GetFrame(0).GetMethod().Name;\n    }\n    public string inlineconstant() {\n        return "inlineconstant";\n    }\n    const string CONSTANT_NAME = "constant";\n    public string constant() {\n        return CONSTANT_NAME;\n    }\n    public string expr() {\n        Expression&lt;Func&lt;methods, string&gt;&gt; ex = e =&gt; e.expr();\n        return ex.ToString();\n    }\n    public string exprmember() {\n        return expressionName&lt;methods,string&gt;(e =&gt; e.exprmember);\n    }\n    protected string expressionName&lt;T,P&gt;(Expression&lt;Func&lt;T,Func&lt;P&gt;&gt;&gt; action) {\n        // https://stackoverflow.com/a/9015598/1037948\n        return ((((action.Body as UnaryExpression).Operand as MethodCallExpression).Object as ConstantExpression).Value as MethodInfo).Name;\n    }\n    public string callermember([CallerMemberName]string name = null) {\n        return name;\n    }\n}\n</code></pre>\n\n<h3>RESULTS</h3>\n\n<p><strong>reflection</strong>\nreflection </p>\n\n<p><strong>stacktrace</strong>\nstacktrace </p>\n\n<p><strong>inlineconstant</strong>\ninlineconstant </p>\n\n<p><strong>constant</strong>\nconstant </p>\n\n<p><strong>expr</strong>\ne => e.expr() </p>\n\n<p><strong>exprmember</strong>\nexprmember </p>\n\n<p><strong>callermember</strong>\nMain </p>\n\n<pre><code>Method name retrieval: (reflection) vs (stacktrace) vs (inlineconstant) vs (constant) vs (expr) vs (exprmember) vs (callermember) \n\n 154673 ticks elapsed ( 15.4673 ms) - reflection\n2588601 ticks elapsed (258.8601 ms) - stacktrace\n   1985 ticks elapsed (  0.1985 ms) - inlineconstant\n   1385 ticks elapsed (  0.1385 ms) - constant\n1366706 ticks elapsed (136.6706 ms) - expr\n 775160 ticks elapsed ( 77.516  ms) - exprmember\n   2073 ticks elapsed (  0.2073 ms) - callermember\n\n\n&gt;&gt; winner: constant\n</code></pre>\n\n<hr>\n\n<p>Note that the <code>expr</code> and <code>callermember</code> methods aren\'t quite "right".  And there you see a repetition of <a href="https://stackoverflow.com/a/2652516/1037948">a related comment</a> that reflection is ~15x faster than stacktrace.</p>\n'}, {'answer_id': 33020480, 'author': 'SharK', 'author_id': 2841325, 'author_profile': 'https://Stackoverflow.com/users/2841325', 'pm_score': 3, 'selected': False, 'text': '<p>The simple way to deal is:</p>\n\n<pre><code>System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name;\n</code></pre>\n\n<p>If the System.Reflection is included in the using block:</p>\n\n<pre><code>MethodBase.GetCurrentMethod().DeclaringType.FullName + "." + MethodBase.GetCurrentMethod().Name;\n</code></pre>\n'}, {'answer_id': 34505798, 'author': 'Adriano Silva Ribeiro', 'author_id': 5034536, 'author_profile': 'https://Stackoverflow.com/users/5034536', 'pm_score': 0, 'selected': False, 'text': '<p>Try this...</p>\n\n<pre><code>    /// &lt;summary&gt;\n    /// Return the full name of method\n    /// &lt;/summary&gt;\n    /// &lt;param name="obj"&gt;Class that calls this method (use Report(this))&lt;/param&gt;\n    /// &lt;returns&gt;&lt;/returns&gt;\n    public string Report(object obj)\n    {\n        var reflectedType = new StackTrace().GetFrame(1).GetMethod().ReflectedType;\n        if (reflectedType == null) return null;\n\n        var i = reflectedType.FullName;\n        var ii = new StackTrace().GetFrame(1).GetMethod().Name;\n\n        return string.Concat(i, ".", ii);\n    }\n</code></pre>\n'}, {'answer_id': 45594089, 'author': 'michael kosak', 'author_id': 8440225, 'author_profile': 'https://Stackoverflow.com/users/8440225', 'pm_score': 2, 'selected': False, 'text': '<p>I just did this with a simple static class:</p>\n<pre><code>using System.Runtime.CompilerServices;\n.\n.\n.\npublic static class MyMethodName\n{\n    public static string Show([CallerMemberName] string name = &quot;&quot;)\n    {\n        return name;\n    }\n}\n</code></pre>\n<p>then in your code:</p>\n<pre><code>private void button1_Click(object sender, EventArgs e)\n{\n    textBox1.Text = MyMethodName.Show();\n}\n\nprivate void button2_Click(object sender, EventArgs e)\n{\n    textBox1.Text = MyMethodName.Show();\n}\n</code></pre>\n'}, {'answer_id': 57527607, 'author': 'Baglay Vyacheslav', 'author_id': 1361923, 'author_profile': 'https://Stackoverflow.com/users/1361923', 'pm_score': -1, 'selected': False, 'text': '<pre><code>new StackTrace().ToString().Split("\\r\\n",StringSplitOptions.RemoveEmptyEntries)[0].Replace("at ","").Trim()\n</code></pre>\n'}, {'answer_id': 62810747, 'author': 'mr R', 'author_id': 1831734, 'author_profile': 'https://Stackoverflow.com/users/1831734', 'pm_score': 2, 'selected': False, 'text': '<pre><code>using System;\n                    \npublic class Program\n{\n    public static void Main()\n    {\n        \n        Console.WriteLine(&quot;1: {0} {1}&quot;, System.Reflection.MethodBase.GetCurrentMethod().Name, System.Reflection.MethodBase.GetCurrentMethod().ReflectedType);\n        OtherMethod();\n    }\n    \n    public static void OtherMethod()\n    {\n        Console.WriteLine(&quot;2: {0} {1}&quot;, System.Reflection.MethodBase.GetCurrentMethod().Name, System.Reflection.MethodBase.GetCurrentMethod().ReflectedType);\n    }\n}\n</code></pre>\n<p>Output:</p>\n<pre><code>1: Main Program\n2: OtherMethod Program\n</code></pre>\n'}, {'answer_id': 63949974, 'author': 'Romerik Rousseau', 'author_id': 2335803, 'author_profile': 'https://Stackoverflow.com/users/2335803', 'pm_score': 1, 'selected': False, 'text': '<p>Add this method somewhere and call it without parameter!</p>\n<pre><code>public static string GetCurrentMethodName([System.Runtime.CompilerServices.CallerMemberName] string name = &quot;&quot;)\n{\n    return name;\n}\n</code></pre>\n'}, {'answer_id': 66869691, 'author': 'Chef Gladiator', 'author_id': 10870835, 'author_profile': 'https://Stackoverflow.com/users/10870835', 'pm_score': 2, 'selected': False, 'text': '<p>A bit more resilient, solution for customers from 2021,2022:</p>\n<pre><code>namespace my {\n   public struct notmacros\n   {\n\n[MethodImpl(MethodImplOptions.AggressiveInlining)]\npublic static string \n  whoami( [CallerMemberName] string caller_name = null)\n  {\n     if (string.IsNullOrEmpty(caller_name)) \n        return &quot;unknown&quot;;\n     if (string.IsNullOrWhiteSpace(caller_name)) \n        return &quot;unknown&quot;;\n     return caller_name;\n  }\n }\n} // my namespace\n</code></pre>\n<p>Usage</p>\n<pre><code>using static my.notmacros\n // somewhere  appropriate\n var my_name = whoami() ;\n</code></pre>\n<p>.NET fiddle link for the actual demo:</p>\n<p><a href="https://dotnetfiddle.net/moK73n" rel="nofollow noreferrer">https://dotnetfiddle.net/moK73n</a></p>\n<p>Please note the compiler requirement: .NET 6</p>\n'}, {'answer_id': 67372375, 'author': 'Useme Alehosaini', 'author_id': 13121879, 'author_profile': 'https://Stackoverflow.com/users/13121879', 'pm_score': 3, 'selected': False, 'text': "<p>For <code>Async</code> Methods, you can use:</p>\n<pre><code>//using System.Reflection;\n\nvar myMethodName = MethodBase\n                    .GetCurrentMethod()\n                    .DeclaringType\n                    .Name\n                    .Substring(1)\n                    .Split('&gt;')[0];\n</code></pre>\n"}, {'answer_id': 68122310, 'author': 'Paul Williams', 'author_id': 420400, 'author_profile': 'https://Stackoverflow.com/users/420400', 'pm_score': 2, 'selected': False, 'text': "<p>To handle both async and plain old method calls, I did this.</p>\n<p>In my application, it's only getting called from exception handlers, so perf is not a concern.</p>\n<pre><code>[MethodImpl(MethodImplOptions.NoInlining)]\npublic static string GetCurrentMethodName()\n{\n    var st = new StackTrace();\n    var sf = st.GetFrame(1);\n    string name = sf.GetMethod().Name;\n\n    if (name.Equals(&quot;MoveNext&quot;))\n    {\n        // We're inside an async method\n        name = sf.GetMethod().ReflectedType.Name\n                 .Split(new char[] { '&lt;', '&gt;' }, StringSplitOptions.RemoveEmptyEntries)[0];\n    }\n\n    return name;\n}\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/44153', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3043/']