1

Similar to Finding the variable name passed to a function

The main difference is that I'm using a variable passed by reference, and in particular, I don't actually have an object instance at the time that I'm calling the nameof function

For example:

class blank 
{
}
class Program
{

   static blank yes;

    static void test<T>(ref T no)
    {
        Console.WriteLine(nameof(no));  //outputs no
    }

    static void Main(string[] args)
    {
        test(ref yes);
    }
}

Is there a way to get "yes" printed instead of "no"? It feels like because I'm passing it by reference, there should be a way I can get at the actual name somehow.

yhyrcanus
  • 3,743
  • 2
  • 23
  • 28
  • 1
    `ref` referrers to the variable's memory address, not its c# name. – gunr2171 Mar 11 '21 at 21:42
  • Yep. And i was thinking that if i have the original object address, there should be a way to get at the original variable name using reflection somehow. – yhyrcanus Mar 11 '21 at 21:48
  • 3
    Still don't think it's possible: https://stackoverflow.com/questions/58065439/how-to-get-nameof-of-the-passed-parameter-inside-of-the-method "The reason why it's not possible is because the variable name is not included in the compiled IL output." – gunr2171 Mar 11 '21 at 21:50
  • 1
    @gunr2171 Even if you had a PDB, which *does* include local variable names, you still cannot, because in a lot of cases it is optimized away, for example into a register. The function itself may not exist. It is possible to do it in some circumstances with the debugger API, but let's not go there. – Charlieface Mar 11 '21 at 21:53
  • 2
    When you pass by ref you are actually creating a second name for the same reference, so by your logic, a memory address would have to maintain a list of variable names. Nope, it is a one-direction situation. – Crowcoder Mar 11 '21 at 21:53
  • @gunr2171 Furthermore, it may be the same location as another variable from a different part of the function. It is simply not even correct to consider the reference to be an actual memory address that is possible to be interrogated as to what its name is. *EDIT* both agreeing and correcting (being pedantic you might say) – Charlieface Mar 11 '21 at 22:01
  • @Charlieface sorry, I'm confused. Are you correcting me or giving additional information based on my message? – gunr2171 Mar 11 '21 at 22:02

0 Answers0