C#: 15-Events

Declare the event at the class level

public static event Action Triggered;

Fire the Action

Triggered();

Add event listener method

        void HasTriggered()
        {
            Console.WriteLine("Survey Triggered, run stats");
        }


 

Register the event listener in a method

        public void Start()
        {
            Survey.Triggered += HasTriggered;
        }


 

When Triggered() is called


 

Definition Class with Inititlization and Caller

Add the event to class fields and give name

Instantiate the Implementation Class that will do something as a result of the event firing

    public class Survey
    {
        public static event Action Triggered;
        public static void AskSurvey()
        {
            Stats stats = new Stats();
            stats.Start();


            Data data = new Data();

            Console.WriteLine("What is your name?");
            data.Name = TryAnswer();

            Console.WriteLine("What is your age?");
            data.Age = int.Parse(TryAnswer());

            Console.WriteLine("What is your birth month?");
            data.Month = TryAnswer();

            Triggered();
            data.Display();
        }


 


 

Implentation Class

Add the event listener from the definition class

Add the method that gets called when event is fired

using System;
using System.Collections.Generic;
using System.Text;

namespace Basics.Projects.Survey
{
    class Stats
    {
        // to add/activate the listener add to a method
        // once this method is called, anytime the 'Triggered' is encountered, 
        //   the HasTriggered() method is called
        public void Start()
        {
            Survey.Triggered += HasTriggered;
        }

        void HasTriggered()
        {
            Console.WriteLine("Survey Triggered, run stats");
        }
    }
}


 

Output

What is your name?
Name
What is your age?
21
What is your birth month?
May
Survey Triggered, run stats
Your name is Name
Your age is 21
Your birth month is May
Sign is Taurus


 

if Survey.Triggered is not Registered, the following error is thrown

What is your name?
name
What is your age?
21
What is your birth month?
May

Unhandled Exception: System.NullReferenceException: Object reference not set to
an instance of an object.
   at Basics.Projects.Survey.Survey.AskSurvey() in C:\Users\silosix\source\repos
\CEssentials2018\Survey\Projects\Survey\Survey.cs:line 52
   at Basics.Program.Survey_Runner() in C:\Users\silosix\source\repos\CEssential
s2018\Survey\Program.cs:line 71
   at Basics.Program.Run() in C:\Users\silosix\source\repos\CEssentials2018\Surv
ey\Program.cs:line 18
   at Basics.Program.Main(String[] args) in C:\Users\silosix\source\repos\CEssen
tials2018\Survey\Program.cs:line 10


 

Add a null check to the event caller to ensure something has been registered to it

if(Triggered != null)
{
    Triggered();
}

 

Simplified event code

Triggered?.Invoke();
Tags