Delegates and Events in C#

 Delegates and Events in C#


Delegates are type-safe function pointers that allow a program to pass methods as arguments to other methods. Events are a way for an object to notify other objects when something happens. Here's an example code that demonstrates how to define a delegate and raise an event:


delegate void EventHandler();


class Button

{

    public event EventHandler Click;


    public void OnClick()

    {

        if (Click != null)

        {

            Click();

        }

    }

}


class Program

{

    static void Main(string[] args)

    {

        Button btn = new Button();


        btn.Click += () =>

        {

            Console.WriteLine("Button clicked.");

        };


        btn.OnClick();  // raises the Click event

    }

}

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...