How to Make Something a Fire Off Action Event

How to Make Something a Fire Off Action Event thumbnail
When an event occurs, it is said to have "fired."

Most programming terms sound dry, but the terms programmers use to describe events are uncharacteristically vivid. Programmers speak of making an event "fire" in response to a user action, for example. Perhaps programmers use colorful language to describe events because events lie at the core of any application. In your own applications, you can use an event to make your code respond to a change in existing conditions. You can readily adopt the following code sample, written in the popular C# programming language, for use in any other programming framework.

Instructions

    • 1

      Open a text editor or the programming software of your choice and find the class that must contain the event.

    • 2

      Declare the event using the Public and Event keywords. Use the EventHandler delegate type in the event declaration. Write the name of the event after the EventHandler delegate:

      public event EventHandler SampleEvent;

    • 3

      Invoke the event using point notation, exactly as you would if calling a function. Before invoking the event, ensure that at least one method is subscribed to it -- in other words, make certain that the event isn't empty. Place the invocation inside a method, which will fire the event.

      private void sampleMethod(object source, EventArgs args)
      {
      if (sampleEvent != null)
      sampleEvent(source, args);
      }

    • 4

      Add code to execute when the event fires. Add a method to the event using the "+=" operator to subscribe a function to an event:

      SampleClass.SampleEvent += MyClass.MethodToAddToEvent;

    • 5

      Save and test your work to ensure it performs as expected.

Related Searches:

References

Resources

  • Photo Credit Hemera Technologies/AbleStock.com/Getty Images

Comments

Related Ads

Featured