C# Trigger and event when there is a change in a variable

Erci Cheung 21 Reputation points
2022-01-20T15:15:54.053+00:00

Total noob to C# and don't really have a good grasp of delegate and events. I want to trigger an event when a variable is changed and run some method/function when it is triggered in the same class. Not sure if events are best way to do this but if could use some help on this to better understand it. Here is some sample code online I was trying out but not sure how to use and implement in the class or main().

private int _age;

//#1
public event System.EventHandler AgeChanged;

//#2
protected virtual void OnAgeChanged()
{
if (AgeChanged != null) AgeChanged(this,EventArgs.Empty);
}

public int Age
{
get
{
return _age;
}

set
{
     //#3
     _age=value;
     OnAgeChanged();
}

}

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,249 questions
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 56,026 Reputation points
    2022-01-21T17:53:57.977+00:00

    its really pretty simple. event handling generally defined as registering a callback to be called when an event happens.

    because C# is strongly typed, you need a way to define return type and parameter types of the callback. this is done with a delegate, which defines the callback signature.

    because event handling is so common, there is a system event class that supports multicasting (registering multiple callbacks).

    first define the message, which inherits from EventArgs

    public class AgeEventArgs : EventArgs {public int Age; }
    

    Now define the the callback signature using a delegate that has two parameter , object and EventArgs:

    public delegate void AgeChangedHandler (object source, AgeEventArgs e);
    

    now define the event, which allow registering the callbacks

    public event AgeChangedHandler OnAgeChanged;
    

    when the event happens we need to invoke the callbacks if any (thus the null check)

    AgeChanged?.Invoke(this, new AgeEventArgs{ Age = _age});
    

    it is common to provide a virtual method for this but not required.

    you then create a class instance and register the callback

    var a = new MyClass();
    a.AgeChanged += (o,e) => Console.WriteLine(e.Age);
    

    another option is to just expose a delegate via the Action<> or Func<> generic, and call the delegate. you can define your parameters

    public Action<MyClass2, int> OnAgeChanged;
    

    and just call

    this?.OnAgeChanged(this, _age);
    

    here is a complete .net program doing both methods:

    using System;
    public class Program
    {
        public class MyClass
        {
            private int _age;
            public class AgeEventArgs : EventArgs
            {
                public int Age {get; set;}
            }
            public delegate void AgeChangedHandler (object source, AgeEventArgs e);
            public event AgeChangedHandler AgeChanged;
            protected virtual void OnAgeChanged()
            { 
                AgeChanged?.Invoke(this, new AgeEventArgs{ Age = _age});
            }
            public int Age
            {
                get { return _age; }
                set
                {
                    _age = value;
                    OnAgeChanged();
                }
            }
        }
    
        public class MyClass2
        {
            private int _age;
            public Action<MyClass2, int> OnAgeChanged;
            public int Age
            {
                get { return _age; }
                set
                {
                    _age = value;
                    this?.OnAgeChanged(this, _age);
                }
            }
        }
    
        public static void Main()
        {
            var a = new MyClass();
            a.AgeChanged += (o,e) => Console.WriteLine(e.Age);
            a.Age = 10;
    
            var b = new MyClass2();
            b.OnAgeChanged = (source,age) => Console.WriteLine(age);
            b.Age = 11;
        }
    }
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful