-1

For example, I have such method:

public void ExecuteExampleMethod()
{
    var exampleId1 = 1;
    var exampleId2 = 2
    ExampleMethod(0, exampleId1, exampleId2)
}

public void ExampleMethod(int exampleId, params object[] parameters)
{
   foreach(var parameter in parameters)
   {
     Console.WriteLine($"{parameter.Name} {parameter.Value}")
   }
   
}
  

So, I need to output like this:

"exampleId1 1"
"exampleId2 2"

How can I do it? I tried reflection = parameter.GetType() - but didn't find anything useful.

  • 2
    You can't get the variable name, since it's not part of the object. Why not use a `Dictionary`? – Magnetron Jun 14 '21 at 12:18
  • You're going off down the wrong path. Objects don't have "names" based on the first variable that happened to reference them. In general, an object may be referenced from multiple locations (variables, contained in an array, etc) each of which has independent naming (or no naming, in the case of the array) – Damien_The_Unbeliever Jun 14 '21 at 12:19
  • 3
    This sounds mightily like an [XY Problem](http://xyproblem.info) – Jamiec Jun 14 '21 at 12:19
  • 1
    What would be the names if the method is called like this : `ExampleMethod(0, 1, 2);`? – Cid Jun 14 '21 at 12:20
  • 2
    @AtlasPromotion Another way is pass an tupple `(nameof(variable),value)` instead of the value only – Magnetron Jun 14 '21 at 12:21
  • Does this answer your question? [get name of a variable or parameter](https://stackoverflow.com/questions/9801624/get-name-of-a-variable-or-parameter) and [How to get variable name using reflection?](https://stackoverflow.com/questions/2566101/how-to-get-variable-name-using-reflection) 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) and [Create dynamic variable name](https://stackoverflow.com/questions/20857773/) –  Jun 14 '21 at 12:27

1 Answers1

-1

Used Dictionary<string, object>.