Jump to content
  • Advertisement
Sign in to follow this  
MarcoKotrotsos

Events in c#

This topic is 4833 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

evening all... My quest this week was learning OO in C# (and oo in general, see other threads) But i came to the inevitable delegates/events chapter now and i'm lost. I just can't seem to find a very simple working sample on how this works. And i don't mean the onclick events but genuin eventhandlers like when a number get's above 50 it call's an eventhandler.. could someone pretty please(with sugar on top) provide me with a working sample guiding me through this? Thank you very much kindest regards, Marco

Share this post


Link to post
Share on other sites
Advertisement
Just step through using the debugger:

public class FuelLowEventArgs : EventArgs
{
private int fuelLevel;
public int FuelLevel
{
get
{
return fuelLevel;
}
}
public FuelLowEventArgs(int fuelLevel)
{
this.fuelLevel = fuelLevel;
}
}
public delegate void FuelLowEventHandler(object sender, FuelLowEventArgs e);

public class Passenger
{
public Passenger(Car car)
{
car.FuelLow += new FuelLowEventHandler(car_FuelLow);
}
private void car_FuelLow(object sender, FuelLowEventArgs e)
{
Console.WriteLine("Passenger in panic");
}
}

public class Driver
{
public Driver(Car car)
{
car.FuelLow += new FuelLowEventHandler(car_FuelLow);
car.Start();
}

private void car_FuelLow(object sender, FuelLowEventArgs e)
{
((Car)sender).Fill(20);
}

public static void Main()
{
Car bug = new Car();
Passenger friend = new Passenger(bug);
Driver me = new Driver(bug);
Console.ReadLine();
}
}

public class Car
{
private int fuelLevel = 30;
public event FuelLowEventHandler FuelLow;

protected void OnFuelLow(int fuelLevel)
{
if(FuelLow != null)
{
FuelLow(this, new FuelLowEventArgs(fuelLevel));
}
}

public void Fill(int amount)
{
fuelLevel += amount;
}

public void Start()
{
while(fuelLevel > 0)
{
fuelLevel--;
if(fuelLevel < 5)
{
OnFuelLow(fuelLevel);
}
Console.WriteLine("Fuel remaining: " + fuelLevel.ToString());
System.Threading.Thread.Sleep(100);
}
}
}




[Edited by - ernow on July 27, 2005 8:27:09 AM]

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!