How to use Simple Event in C#

In this article, I want to create an application that will inform to your parents when your GPA score is published.


class Program
{
static void Main(string[] args)
{
Student oStudent = new Student();
oStudent.Name = "James";
oStudent.GPAScore = 80;

Parent oParent = new Parent();
oParent.Name = "Daddy Cool";

oStudent.NotifyToParent += new NotifyGpaDelegate(oParent.NotifyMe);
oStudent.RecordGPAScore();
}
}

public delegate void NotifyGpaDelegate(int GPAScore);

class Student
{
public event NotifyGpaDelegate NotifyToParent;
public String Name { get; set; }
public int GPAScore { get; set; }
public void RecordGPAScore()
{
if (NotifyToParent != null)
NotifyToParent(GPAScore);
}
}

class Parent
{
public String Name { get; set; }
public void NotifyMe(int pGPAScore)
{
Console.WriteLine(String.Format("{0} notified about the GPA {1}",Name, pGPAScore.ToString()));
}
}


In the program, if you want to use anonymous method then you can change the main program like


class Program
{
static void Main(string[] args)
{
Student oStudent = new Student();
oStudent.Name = "James";
oStudent.GPAScore = 80;

oStudent.NotifyToParent += 
delegate(int pGPAScore)
{
Console.WriteLine(String.Format("{0} notified about the GPA {1}", "Dad", pGPAScore.ToString()));
};
oStudent.RecordGPAScore();
}
}

Ebook Download
View all
Learn
View all