C# event is null

15,151

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.

Share:
15,151
Clock
Author by

Clock

Updated on July 27, 2022

Comments

  • Clock
    Clock almost 2 years

    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.

  • mason
    mason almost 11 years
    To add to this, you should always check if it's null before trying to fire the event in case there is no attached handler.
  • Clock
    Clock almost 11 years
    Thank you for comment, it help me to solve the issue, moving the event raising to the Speed property and assign the property a value after the event handler was added is raising the event as expected ! Also using a static event and assigning the event handler before the car instantiation toked place and raising the event from the Car constructor worked fine ! Thank you for your explanations !