0

I want to get the variable name of an argument passed into a method.

// Somewhere in the code
int myNumber = 1;
Method(myNumber);

...

public void Method(int number)
{
    // Here I want to somehow get "myNumber" as well as access the value '1'.
}

I haven't had any success finding an answer to this question. Many answers says no, but that is back when C# 6 was the latest version. Maybe there is a solution today?

I imagine that passing by reference ref could be relevant, as that at least ensures that a variable is passed in the method, and not just the value.

MatthiasA
  • 381
  • 4
  • 11
  • 1
    Why don't you just pass the name of the variable as another parameter? It would be interesting to know what problem you're trying to solve. If what you want is possible - and I'm not at all sure it is - it would have to be by some form of reflection I imagine. – SBFrancies Jan 22 '21 at 20:55
  • 1
    Does this answer your question? [Finding the variable name passed to a function](https://stackoverflow.com/questions/72121/finding-the-variable-name-passed-to-a-function) and [How to check if the parameter of a method comes from a variable or a literal?](https://stackoverflow.com/questions/65754778/how-to-check-if-the-parameter-of-a-method-comes-from-a-variable-or-a-literal/65754971) –  Jan 22 '21 at 21:01
  • This is not supported yet, though some base work was done a few years (! *sigh*) ago: https://github.com/dotnet/csharplang/issues/287 – NetMage Jan 22 '21 at 21:22
  • @OlivierRogier Thanks for answer. The problem is that the first linked question is from 2008. Most answers are as well. – MatthiasA Feb 02 '21 at 09:49
  • @SBFrancies I am trying to make a simple expectation library, where you can make NotNull, NotNullOrWhitespace, GreatherThan (and so on) statements with a single line. The argument exceptions thrown by those methods should include the variable name inputted by the developer. I know the nameof trick, but that means you have to include that with every single statement. – MatthiasA Feb 02 '21 at 09:50

0 Answers0