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;
}
}