0

I have a parameter d. I want to use the name of the parameter in an error message:

void foo(string d)
{
    // this does not work
    string message string.Format("Parameter {0} is missing please verify inputs", d));
} 

How can I get the name of a parameter?

Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
Andrei Paul
  • 83
  • 1
  • 1
  • 9

3 Answers3

2

You can use nameof:

string nameOfD = nameof(d);

Note that this will not give the name of the variables used to call a method, it just works for the local variable. In this case, nameof will always return "d".

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
2

You can use Lambda expressions:

static void Main( string[] args ) {
    int A = 50, B = 30, C = 17;
    Print( () => A );
    Print( () => B );
    Print( () => C );
}

static void Print<T>( System.Linq.Expressions.Expression<Func<T>> input ) {
    System.Linq.Expressions.LambdaExpression lambda = (System.Linq.Expressions.LambdaExpression)input;
    System.Linq.Expressions.MemberExpression member = (System.Linq.Expressions.MemberExpression)lambda.Body;

    var result = input.Compile()();
    Console.WriteLine( "{0}: {1}", member.Member.Name, result );
}

Try this one.

vasanths294
  • 1,457
  • 2
  • 13
  • 29
2

You could use a concatenation of String.IsNullOrEmpty(variable)?nameof(variable):String.Empty. So you'd get

var str = String.Join(',', new List<String> 
  {
    String.IsNullOrEmpty(a)?nameof(a):String.Empty,
    String.IsNullOrEmpty(b)?nameof(b):String.Empty,
    String.IsNullOrEmpty(c)?nameof(c):String.Empty,
    String.IsNullOrEmpty(d)?nameof(d):String.Empty
});
string.Format("Parameter {0} is missing please verify inputs", str);
Hintham
  • 1,078
  • 10
  • 29