-9

Imagine I have an int count, and every time it gets changed i want to call the function DoSomething() how could i do it?

I think i have to use properties somehow (and would like how to know how to do it with a property), but any help will be great.

Qiqete
  • 11
  • 4

1 Answers1

1

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

Rufus L
  • 36,127
  • 5
  • 30
  • 43