SoFunction
Updated on 2025-03-08

C# Summary of defining and using custom event methods in a program

C# defines and uses custom events in a program and can be divided into the following steps:

Step 1: Define events in class

using System;

public class TestClass

{

  //....

  public event EventHandler TestEvent

}

Step 2: Define event parameters

Note: The event parameter class TestEventArgs inherits from

using System;

public class TestEventArgs : EventArgs

{

  public TestEventArgs() : base() { }

 

  public string Message { get; set; }

}

Step 3: Raise an event in TestClass

public class TestClass

{

  // This method causes an event
  public void RaiseTestEvent(string message)

  {

    if (TestEvent == null) return;

    TestEvent(this, new TestEventArgs { Message = message });

  }

  public event EventHandler TestEvent; 

}

Step 4: Use events

class Program

{

  static void Main(string[] args)

  {

 

    TestClass tc = new TestClass();

    // How to handle hook event
     += Tc_TestEvent;

     

    ("Press any key to raise an event");

    ();    

    // Raise an event
    ("String passed through event parameters");

     

    ("Press any key to exit");

    ();

  }

  private static void Tc_TestEvent(object sender, EventArgs e)

  {

    // Cast event parameters to TestEventArgs
    TestEventArgs te = (TestEventArgs)e;

    // Display Message in event parameters
    ();

  }

}

The complete procedure is as follows

using System;

public class TestClass

{

  public void RaiseTestEvent(string message)

  {

    if (TestEvent == null) return;

    TestEvent(this, new TestEventArgs { Message = message });

  }

 

  public event EventHandler TestEvent; 

}

public class TestEventArgs : EventArgs

{

  public TestEventArgs() : base() { }

 

  public string Message { get; set; }

}

class Program

{

  static void Main(string[] args)

  {

 

    TestClass tc = new TestClass();

     += Tc_TestEvent;

    ("Press any key to raise an event");

    ();

    ("String passed through event parameters");

    ("Press any key to exit");

    ();

  }

  private static void Tc_TestEvent(object sender, EventArgs e)

  {

    TestEventArgs te = (TestEventArgs)e;

    ();

  }

}