Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Short answer: No, there isn't. (Is that terse enough? ;)</p> <p>(EDIT: Justin's answer probably counts. It leaves a bad taste in my mouth, but it accomplishes the goal of "no need to put the parameter name into a string". I don't think I'd really count AOP though, as that's really changing to a completely different approach rather than answering the original question of getting a parameter name from within a method.)</p> <p>Longer answer: There's a way to find out <em>all the parameters</em> of a method, but I don't think it's useful in this case.</p> <p>Here's an example which displays the parameter names from a couple of methods:</p> <pre><code>using System; using System.Reflection; class Test { static void Main() { Foo(null); Bar(null); } static void Foo(object resource) { PrintParameters(MethodBase.GetCurrentMethod()); } static void Bar(object other) { PrintParameters(MethodBase.GetCurrentMethod()); } static void PrintParameters(MethodBase method) { Console.WriteLine("{0}:", method.Name); foreach (ParameterInfo parameter in method.GetParameters()) { Console.WriteLine(" {0} {1}", parameter.ParameterType, parameter.Name); } } } </code></pre> <p>So that does that, but if you have multiple parameters and you wanted to throw an appropriate exception, how would you know (in a safe way) which to use? Ideally you want something like:</p> <pre><code>public void Woof(object resource) { if (resource == null) { throw new ArgumentNullException(infoof(resource)); } // .. } </code></pre> <p>where the mythical <code>infoof</code> operator would return a <code>ParameterInfo</code>. Unfortunately this doesn't exist.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload