How to programmatically determine a parameter name when building an ArgumentException?

When an ArgumentException is thrown, a pair of overloads takes a string, which is an invalid argument parameter name. I believe that it would be nice to remember to update this ctor parameter when changing the name of the method parameter. Is there an easy way to do this with reflection?

Update: thanks to two respondents. You both answer the question well, but the solution still leaves me with a maintenance headache. (Well, the headache is tiny , but still ...) To explain, if later I had to change the order of the parameters - or delete the previous parameter - I would have to remember to change my exception - the construction code. Is there a way I can use something in strings

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

to make sure I'm dealing with the appropriate parameter? Thus, the compiler must intervene so that I cannot badly construct the exception.

However, I am beginning to suspect that the “simple” part of the original question is not what is expected. Maybe I should just use string literals. :)

+3
2

.

, .

, FxCop ( Team Code Code Analysis) , .

+2

, . .

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

NameOfVariable :

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

, , UnaryExpression, NameOfVariable.

, FxCop , Joe , FxCop - , , .

+2

Source: https://habr.com/ru/post/1697136/


All Articles