Home > other >  How To Call Variable Name From Another Class C#
How To Call Variable Name From Another Class C#

Time:11-27

Example of the code

class Main{
        Name Jack = new Name();
        Jack.Speak();
}

class Name{
     public string speak(){
        Console.WriteLine("Hello", valuename);
      }
      
     public Name()
     {
       valuename = nameof(Jack); 
     }
}

Output the what im searching for:

Hello Jack. 

If user types Name Joe = new Name(); output will be Hello Joe.

CodePudding user response:

Local variable names are syntactical sugar that is mostly thrown away by the compiler, so there's no direct way to do this.

The closest you can get is using [CallerArgumentExpression] to have the compiler capture the source code expression that was passed to a parameter, but this only works for method arguments and will capture the entire expression, not just the variable name. For example, the following program will print jack then jack "hello":

using System;
using System.Runtime.CompilerServices;

class Program {
    static void Main()
    {
        var jack = "dummy";
        WriteExpression(jack);
        WriteExpression(jack   "hello");
    }

    static void WriteExpression(
        string param, 
        [CallerArgumentExpression("param")] string paramExpression = null
    ) => Console.WriteLine(paramExpression);
}
  • Related