C# Built in Delegates with Programming Example

built-in-delegates
In this chapter you will learn

  • How events return a value?
  • Built in delegates in c#
  • Programming Example

Built in Delegates in C#

In the previous chapter we learned to create custom events in c#. In this chapter you will know how to use in built delegates in c#. Microsoft provides 2 built in delegates to work with.

These built in delegates helps you to write event handling code with ease. With these delegates you can pass one or more than one value to event handler. When you raise event you must follow the discipline and pass required parameters to delegates.

  • Example 1:

    9
    ***Event Executed : This is Odd Number***
    _

    Explanation

    In this program, I have used built in delegates in c#.

    1. Declare built in delegates
    2. Raised Event

      this denotes the current instance of class
      EventArgs.Empty tells that there is empty value in parameter.
    3. Initialize Events in Main function
    4. Calls the methods with required parameters.

    In the above program the events doesn’t return any value. Now, look for the next modified program that returns a value with EventArgs.

    Example 2

    Output

    9
    Event Executed : 9 is an Odd Number
    _

     
    event2

    Let’s understand this example.

      1. I have created a custom OddNumberEventArgs class that inherits the EventArgs. This class simply set the parameter value to sum variable.
      2. Now, created event ev_OddNumber using this class.
      3. Pass required parameter when called this event.
      4. Now in the EventMessage() function; OddNumberEventArgs e has a value.

    Summary

    In this chapter you learned about built in delegates and also learned how to return a value using custom EventArgs class. In the next chapter there are some easy exercise questions on Delegates and Events that will help you to understand event handling more clearly.


    Leave a Reply

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