Search code examples
c#variablesdetect

Detect variable change c#


I've been searching this for a while and I didn't found anything for my problem.

I have a integer:

private static int kills = 0;

I want a function to run when that variable changes. Like, it is 0 now. If it changes to 2, I want a function like OnVarChange that will be called, and that function OnVarChange will return the amount that was changed. In this case 2-0=2, so it will return 2.

Is this possible? How do I do it?

Hope you understand what I just said :p


Solution

  • You need to provide a change mechanism:

    Add:

    public static int Kills{
        get{  return kills; }
        set{
    
            kills = value;
            //change code here...
           }
    }
    

    Only set using this public Kills property. Don't directly change the instance member kills if possible. But there is always an exception.