views:

138

answers:

2

When constructing an ArgumentException, a couple of the overloads take a string that is the invalid argument's parameter name. I figure it would be nice to not have to remember to update this ctor param whenever I change the method's param name. Is there a simple way to do this using reflection?

Update: thanks to the 2 respondents so far. You both answer the question well, but the solution still leaves me with a maintenance headache. (Okay, a tiny headache, but still...) To explain, if I were to reorder the params later -- or remove an earlier param -- I'd have to remember to change my exception-construction code again. Is there a way I can use something along the lines of

Object.ReferenceEquals(myParam, <insert code here>)

to be sure I'm dealing with the relevant parameter? That way, the compiler would step in to prevent me badly constructing the exception.

That said, I'm starting to suspect that the "simple" part of the original question not that forthcoming. Maybe I should just put up with using string literals. :)

+2  A: 

Reflection is not appropriate for this.

You'll have to put up with remembering to get it right.

Fortunately FxCop (or Team System Code Analysis) will help you by pointing out any mismatches.

Joe
Fair enough - I wasn't sure, as I've barely touched upon reflection before. Good tip on the FxCop thing too. Thanks. :)
Mal Ross
A: 

You could use an expression tree for this, which will get you want you want at the expensive of some odd syntax. E.g.

public void Resize(int newSize)
{
  if (newSize < 1)
  {
    throw new ArgumentException("Blah", NameOfVariable(() => newSize));
  }
  // ... whatever ...
}

Where NameOfVariable is defined as:

public static string NameOfVariable(Expression<Func<object>> expressionTree)
{
   var expression = (UnaryExpression)expressionTree.Body;
   var memberExpression = (MemberExpression)expression.Operand;
   return memberExpression.Member.Name;
}

This also has the chance of crashing at runtime if you pass anything other than a UnaryExpression to NameOfVariable.

I wouldn't be surprised if this code also causes FxCop to complain, and as Joe mentions using FxCop is the probably the best way of doing this.

Wilka