Delegates
Delegates
Delegates
Klent John D. Juaniza
What is a Delegate?
A delegate in C# is a type that represents
a reference to a method with a specific
signature (return type and parameters).
Delegates allow methods to be passed as
parameters, enabling dynamic method
calls, event handling, and callback
mechanisms.
Declare Delegates
Return Type
Access Modifier
Keyword
Name Parameters
Initiate & Invoke Delegates
Initiate & Invoke Delegates (cont..)
Multicasting
A delegate can call more than one method when invoked.
Multicasting (cont..)
Delegate Interface
It can be applied to one method at a time. If a class implements an interface, then it will
implement all the methods related to that
interface.
If a delegate available in your scope you can Interface is used when your class implements
use it. that interface, otherwise not.
Delegates can me implemented any number of Interface can be implemented only one time.
times.
It is used to handling events. It is not used for handling events.
Below are some differences between the Delegates and Interfaces in C#:
Delegate Interface
When you access the method using delegates When you access the method you need the
you do not require any access to the object of object of the class which implemented an
the class where the method is defined. interface.
It can wrap static methods and sealed class It does not wrap static methods and sealed
methods class methods..
Delegate Interface
It can implement any method that provides the If the method of interface implemented, then
same signature with the given delegate. the same name and signature method
override.
It can wrap any method whose signature is A class can implement any number of
similar to the delegate and does not consider interfaces, but can only override those
which from class it belongs. methods which belongs to the interfaces.
C#: Event Declaration and Use
Event Accessors
Reference: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/events/
https://www.tutorialsteacher.com/csharp/csharp-event
What is event in C#?
Events enable a class or object to notify
other classes or objects when something
of interest occurs. The class that sends
(or raises) the event is called the
PUBLISHER and the classes that receive
(or handle) the event are called
SUBSCRIBERS.
Event Declaration
An event can be declared in two steps:
• Declare a delegate.
• Declare a variable of the delegate with event keyword.
Delegate
Keyword Event Name
Raise Event
Consume Event
Events have the following properties:
• The publisher determines when an event is raised; the
subscribers determine what action is taken in response to
the event.