Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help understanding Events in C#

Tags:

c#

events

I'm a beginner in C# and having hard times understanding Events in C# .. The book i read (Illustrated C# 2008) gives an example about it , and there are few thing i need to ask about , so i will past the code here and point out the things i don't understand .

public class MyTimerClass
{
   public event EventHandler Elapsed;
   private void OnOneSecond(object source, EventArgs args)  
   {
     if (Elapsed != null)                
     Elapsed(source, args);
   }
}

class ClassA
{
    public void TimerHandlerA(object obj, EventArgs e) // Event handler
    {
        Console.WriteLine("Class A handler called");
    }
}

class ClassB
{
    public static void TimerHandlerB(object obj, EventArgs e) // Static
    {
        Console.WriteLine("Class B handler called");
    }
}

class Program
{
     static void Main( )
     {
         ClassA ca = new ClassA(); // Create the class object.
         MyTimerClass mc = new MyTimerClass(); // Create the timer object.
         mc.Elapsed += ca.TimerHandlerA; // Add handler A -- instance.
         mc.Elapsed += ClassB.TimerHandlerB; // Add handler B -- static.
         Thread.Sleep(2250);
     }
}

Ok, now the line after declaring the event here public event EventHandler Elapsed; which is private void OnOneSecond(object source, EventArgs args) i know that the two line after it is to check if the event contains methods or not , but what is OnOneSecound for ? or when it's called ? or what it's named .. it's not event handler i guess right ? and what's the relationship between Elapsed and OnOneSecond ?

sorry for the newbie question .. and thanks in advance :)

like image 219
rafael Avatar asked Jan 21 '23 19:01

rafael


1 Answers

the OnOneSecond method will be called internally by the MyTimerClass when it needs to invoke the event.

This is a common pattern used by most controls, including the microsoft ones.

Basically you dont need to be checking if the event is set in multiple places, you just do it in this one method then call this method internally to raise the event.

I tend not to pass the event args to the OnXXX method though, for example.

public event EventHandler<EventArgs> SomeEvent;
protected virtual void OnSomeEvent()
{
    if (this.SomeEvent !=null)
    {
        this.SomeEvent.Invoke(this,EventArgs.Empty);
    }
}

then to raise it

this.OnSomeEvent();
like image 186
Richard Friend Avatar answered Jan 31 '23 22:01

Richard Friend