Can anyone show me an example of a delegate and an event?
Go to solution
Solved by Pinguinsan,
namespace DelegateTest
{
public class Car
{
//Note, delegate and event must have the exact same name
public delegate void PositionChanged(int newPosition);
public event PositionChanged positionChangedEvent;
private int m_position;
public Car()
{
this.m_position = 0; //car is at position 0
}
public void driveToPosition(int position)
{
if (this.m_position != position) //check if position changed
{
this.m_position = position;
//Always check event for null before triggering the event
if (this.positionChangedEvent != null)
{
this.positionChangedEvent.Invoke(this.m_position);
}
}
}
}
public class Program
{
static void Main(string[] args)
{
Car car = new Car();
car.positionChangedEvent += Program.onCarPositionChanged; //Hook/subscribe to the event
car.driveToPosition(15);
car.driveToPosition(200);
car.driveToPosition(0);
car.driveToPosition(0); //Will not fire event, because no change in position
car.driveToPosition(10);
Console.ReadKey(); //Pause console to see output
//...etc
}
//Note that the receiving function must have the same type signature as the delegate/event
private static void onCarPositionChanged(int newPosition)
{
Console.WriteLine("The car moved to position {0}", newPosition);
}
}
}
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now