[Solved] How can i call JUST ONCE a function when a variable changes its value? c# [duplicate]


One thing you can do is use a public property for accessing the Count, and store the value of the property in a private backing field. This way you can compare the incoming value in the setter (which is called when someone is setting the Count property) to the current count. If it’s different, then call DoSomething (and update your backing field):

Property with backing field and custom setter

private int count = 0;

public int Count
{
    get
    {
        return count;
    }
    set
    {
        // Only do something if the value is changing
        if (value != count)
        {
            DoSomething();
            count = value;
        }
    }
}

Example Usage

static class Program
{
    private static int count = 0;

    public static int Count
    {
        get
        {
            return count;
        }
        set
        {
            // Only do something if the value is changing
            if (value != count)
            {
                DoSomething();
                count = value;
            }
        }
    }

    private static void DoSomething()
    {
        Console.WriteLine("Doing something!");
    }

    private static void Main()
    {
        Count = 1; // Will 'DoSomething'
        Count = 1; // Will NOT DoSomething since we're not changing the value
        Count = 3; // Will DoSomething

        Console.WriteLine("\nDone!\nPress any key to exit...");
        Console.ReadKey();
    }
}

Output

enter image description here

2

solved How can i call JUST ONCE a function when a variable changes its value? c# [duplicate]