Start New Discussion within our Software Development Community

Hi All,

I want to create a event on a static variable of the class.
The intention is to notify the class whenever the static variable value is changed, so that it can do some processings.

Please help me do this.
Thanks & Regards
Nishant Guarav

Change the static variable to a static property.
You can then call an event handler in the set method.
You will need a static event of a valuechanged delegate.
So that each new instance is notified of the change, they will need to attach to the event.

class MyTestClass
    {
        // delegate method type for value changed event
        public delegate void ValueChanged(int oldvalue, int newvalue);

        // event called when value is changed
        public static event ValueChanged OnValueChanged;

        // static Value property
        private static int _Value;
        public static int Value
        {
            get { return _Value; }
            set 
            {
                // capture old value
                int oldvalue = _Value;
                // update with new value
                _Value = value;
                // notify change to those who want to know
                OnValueChanged(oldvalue, _Value);
            }
        }

        // class constructor
        public MyTestClass()
        {
            // attach to OnValueChanged to be notified when it is updated
            MyTestClass.OnValueChanged += new ValueChanged(MyTestClass_OnCounterChanged);
        }

        // Method run when Notification of value changed received
        void MyTestClass_OnCounterChanged(int oldvalue, int newvalue)
        {
            // do some instance level processing
        }
     
    }

A Note of Caution
A static is a global variable. It is not generally good practice to use global variables.
Are you sure you need a static?

This article has been dead for over six months. Start a new discussion instead.