Hi Guys
NP106 if (Changed != null)
I got the following program from a book.
Anyone knows please explain the reason. What is the significant of if (Changed != null)?.
Please explain.
Thank you
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);
}
public void StudentChanged(object sender, EventArgs e)
{
Console.WriteLine("The student has changed.");
Console.WriteLine(" ID# {0} GPA {1}\n", stu.GetId(), stu.GetGpa());
}
}
class DemoStudentEvent
{
public static void Main()
{
Student oneStu = new Student();
EventListener listener = new EventListener(oneStu);
oneStu.SetId(2345);
oneStu.SetId(4567);
oneStu.SetGpa(3.2);
}
}
/*
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
*/