4
Reply

Why is check necessary?

Maha

Maha

Nov 13 2015 10:37 AM
469
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
*/

Answers (4)