Cress Cress - 3 months ago 16
C# Question

Passing a static variable by reference in a class constructor

public class Gameplay {
public static int count = 0;

AClass aClass = new AClass(ref count);
}

public class AClass {
public int count { get; set; }

public AClass(ref int c) {
this.count = c;
}

public void printCount() {
Console.WriteLine(this.count.ToString());
}
}


I have two classes like the ones above. Suppose the count variable of Gameplay increases in another class that does Gameplay.count++. I want AClass.count to always be equal to Gameplay.count.

Now, surely I could just use Gameplay.count inside AClass but if I have different counts to pass in different instances of AClass it's better to have the reference to the count you want to access. The above example always writes 0 even if Gameplay count has increased.

Answer

What would you expect this code to do?

int c = 0;
int count = c;
c++;

c and count are both references, yet mutating c somehow does not change the value of count.

It's exactly the same situation in your code.

In your code, this line:

this.count = c;

does not copy the reference to c. It copies the value at the time of the assignment to the value-type backing field for count.


You can pass a lambda expression to the constructor if you need AClass to be able to access the value of some arbitrary integer.

public class Gameplay {
   public static int count = 0;

   AClass aClass = new AClass( () => count );
}

public class AClass {
   public int count { get { return this.getCount(); } }
   private readonly Func<int> getCount;

   public AClass(Func<int> getCount) {
       this.getCount = getCount;
   }

   public void printCount() {
       Console.WriteLine(this.count.ToString());
   }
}
Comments