Events vs Delegates in C#

CsharpProgrammingServer Side Programming

C# events are used to resolve the hassles in Delegates. One an easily override Delegate properties and that can eventually lead to errors in the code. To avoid this, C# uses Events and defines wrappers around Delegates.

Events in C#

To use Event, you should define delegate first. Event is a type of Delegate and an example of event can be when a key is pressed.

public delegate voide Demo(String val);     
public event Test TestEvent;   

An event can hold a delegate like this.

this.TestEvent += new Demo (DemoData);

Delegates in C#

A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime.

public delegate void Demo(String val);     
raja
Published on 17-Sep-2018 09:09:58
Advertisements