Search code examples
c#ref

How to get the ref of a variable of a class in C#?


How to get a reference of a variable in a class? I am trying to get a reference of a variable use it elsewhere and need the changes to be reflected in its habitat.

 public class PowerComINC
 {
     static int IMALF1_A = 0; //INSTRUCTOR MALF ID FOR MISC FUNCTION
     static int IMALF2_A = 0; //INSTRUCTOR MALF ID FOR MISC FUNCTION
     static int IMFIRE_A = 0; //INSTRUCTOR MALF ID FOR FIRE 

     public static ref int GetAssociatedGlobals(string variableName)
     {
         // return ref of variableName
     }
}

...

ref int val = ref PowerComINC.GetAssociatedGlobals("IMALF1_A");

val++;

Console.Writeln(PowerComINC.IMALF1_A); //Print 1

Solution

  • How do you do this? Like so:

    ref int val = ref PowerComINC.GetAssociatedGlobals("IMALF1_A");
    val++;
    Console.WriteLine(PowerComINC.IMALF1_A);
    

    Note the use of ref in both the variable declaration and in prefixing to the assignment. (you can also use ref var val = ..., i.e. the type will be implicitly determined, but the ref is still required).

    Where your method is presumably implemented like such:

    public class PowerComINC
     {
         internal static int IMALF1_A = 0; //INSTRUCTOR MALF ID FOR MISC FUNCTION
         internal static int IMALF2_A = 0; //INSTRUCTOR MALF ID FOR MISC FUNCTION
         internal static int IMFIRE_A = 0; //INSTRUCTOR MALF ID FOR FIRE 
    
         public static ref int GetAssociatedGlobals(string variableName)
         {
             switch (variableName)
             {
                case "IMALF1_A":
                    return ref IMALF1_A;
                case "IMALF2_A":
                    return ref IMALF2_A;
                case "IMFIRE_A":
                    return ref IMFIRE_A;
             }
             throw new ArgumentException(nameof(variableName));
         }
    }
    

    However, as HimBromBeere states, there's little point in approaching this problem in this way. The performance degradation of the switch lookup will invariably outweigh any performance benefit of directly mutating a reference variable as small as an int, and now you have no encapsulation of your fields whatsoever.