Categories
Mastering Development

C#: Is it possible for my application to share an event that’s fired inside one of my other classes?

Forgive me if I’m not explaining this correctly, I’m new to programming and I’m not exactly sure what it’s called of if it’s possible.

First let me explain a few things about my class. We’ll call this class TextStats. The TextStats class creates a timer like this:

 private Timer timer;

Later, these values are set to the timer when it is Initialized:

timer = new Timer(1000);
timer.Elapsed += OnTimedEvent;
timer.AutoReset = true;
timer.Enabled = true;

Then I have an event inside my class that’s fired every second, like this:

    private void OnTimedEvent(object sender, ElapsedEventArgs e)
    {
        Console.WriteLine("Timed event has fired!");
    }

I’ll be adding code to it later on, but basically I’m trying to refactor and clean up some code that’s in my main class..

Now, in the program’s main class, I’m creating an instance, I guess it’s called an instance, to the TextStats class:

TextStats textStats = new TextStats();

OK, now here is the part I’m stumped on! The TextStats class fires the timer event like I want, and will run all the code sort of behind the scenes from my main class…. however, I’d like to also be able to “share” TextStats’ timer event inside my main class.

So in other words, my TextStats class still fires the timer event every second like it should, but I’d also like to somehow create an event inside my main class, that the timer event inside my TextStats class will also fire, or share, or piggyback off of, or be attached to… whatever the process is called… LOL.

I imagine it would be something like this in English form:

share event OnTimedEvent from textStats and map it to this.TimedEvent;

public void TimedEvent()
{
   //Additional code to run with OnTimedEvent event from class TextStats
}

OK, I’ve tried to make that as clear as possible. So sorry for the long explanation. Is there someway to do what I want? I didn’t want to show all my code, as I just kind of jumped right in and I’m sure everything’s a mess, I didn’t want people getting too distracted and just wanted to focus on this one thing. Thank you so much for trying to help!

Leave a Reply

Your email address will not be published. Required fields are marked *