Reputation: 984
I am just working on a project in which i need to raise and handle a custom event... i just simplified a little bit the code and got something like this:
class Car
{
public int Speed { get; set; }
public delegate void SpeedTooHigh(string message);
public event SpeedTooHigh OnSpeedToHigh;
public Car(int speed)
{
this.Speed = speed;
if (speed >= 100)
{
if (this.OnSpeedToHigh != null)
{
this.OnSpeedToHigh("Car has a too high speed !");
}
}
}
}
and the main class in which i am using this class:
class Program
{
static void Main(string[] args)
{
Car car = new Car(120, "Red", "Renault");
car.OnSpeedToHigh += OnCarSpeedToHigh;
Console.WriteLine("Test events");
Console.ReadKey();
}
static void OnCarSpeedToHigh(string message)
{
Console.WriteLine(message);
}
}
When i am running this example it seems that all the time the "OnSpeedToHigh" is null in Car class. And i do not understand why since i am creating an instance of this class in main class and set the speed to be greater the 100 so that "this.OnSpeedToHigh("Car has a too high speed !")" to be called.
Is this enough for raising the event, to instantiate the class and set the speed to be greater the 100 for example ?
Please let me know about this.
Upvotes: 13
Views: 22223
Reputation: 203820
You're firing the event in the constructor, but you're not adding an event handler to the event until after the object is constructed.
Since you haven't yet added any event handlers at the time you fire the event, the event is null.
You probably don't want to fire the event in the constructor, you don't want to be using events at all, or you want the event to be static, so that you can add the event handler before the car is constructed.
Upvotes: 19