Please explain why this check is necessary. Problem is highlighted.
using System;
public delegate void ChangedEventHandler(object sender, EventArgs e);
public class Student
{
private int idNum;
private double gpa;
public event ChangedEventHandler Changed;
public int GetId()
{
return idNum;
}
public double GetGpa()
{
return gpa;
}
public void SetId(int num)
{
idNum = num;
OnChanged(EventArgs.Empty);
}
public void SetGpa(double avg)
{
gpa = avg;
OnChanged(EventArgs.Empty);
}
public void OnChanged(EventArgs e)
{
if(Changed != null)
Changed(this, e);//invoking the event
}
}
class EventListener
{
private Student stu;
public EventListener(Student student)//constructor of the EventListener class
{
stu = student;
stu.Changed += new ChangedEventHandler(StudentChanged);
}
private void StudentChanged(object sender, EventArgs e)
{
Console.WriteLine("The student has changed.");
Console.WriteLine(" ID# {0} GPA {1}", stu.GetId(), stu.GetGpa());
Console.WriteLine();
}
}
class DemoStudentEvent
{
static void Main(string[] args)
{
Student oneStu = new Student();
EventListener listener = new EventListener(oneStu);
oneStu.SetId(2345);
oneStu.SetId(4567);
oneStu.SetGpa(3.2);
Console.ReadKey();
}
}
/*
The student has changed.
ID# 2345 GPA 0
The student has changed.
ID# 4567 GPA 0
The student has changed.
ID# 4567 GPA 3.2
*/

Guest UserPosted Nov 16, 2015, 3:14 AM
MahaPosted Nov 16, 2015, 6:40 AM
MahaPosted Nov 13, 2015, 4:07 PM
Can you explain please what can be the reasons for getting NullReferenceException.
Could you able to modify the above program so that it shows it will get NullReferenceException. Because above program executes without if (Changed != null).
Banketeshvar NarayanPosted Nov 13, 2015, 10:49 AM
This ensures that even if Event changes during the course of action you won't get a NullReferenceException.
you can check the below links for more details.
http://stackoverflow.com/questions/672638/use-of-null-check-in-event-handler
http://stackoverflow.com/questions/6291506/check-if-event-has-any-listeners
http://stackoverflow.com/questions/282653/checking-for-null-before-event-dispatching-thread-safe
http://codereview.stackexchange.com/questions/1142/checking-if-an-event-is-not-null-before-firing-it-in-c
Please accept as answer if it helps you