0% found this document useful (0 votes)
10 views24 pages

Understanding Delegates in C#

Uploaded by

633611sse
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views24 pages

Understanding Delegates in C#

Uploaded by

633611sse
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Delegates and Events in C#

Chapter 2
Outline

◼ Introduction

◼ Delegate and Event in C#


◼ Why we Need Delegates?
◼ Defining and Using Delegates
◼ Delegate Methods
◼ Types of Delegates
◼ Anonymous Delegates
◼ Lambda Expression

2
Introduction

◼ Delegates and events are fundamental to any Windows or


Web Application, allowing the developer to "subscribe" to
particular actions carried out by the user.
◼ A delegate is a way of telling C# which method to call
when an event is triggered. For example, if you click a
Button on a form, the program would call a specific
method. It is this pointer that is a delegate.
◼ Delegates are good, as you can notify several methods
that an event has occurred, if you wish so.

3
Delegates
◼ Delegates form the basis of event handling in
C#.
◼ A delegate is an object that can refer to a
method with a pre-defined signature.
❑ A signature is simply the argument list and

return type of the method


❑ Therefore, when we create a delegate, we are
creating an object that can hold a reference to
a method.

4
Why we Need Delegates?

◼ Delegates play a central role throughout the .NET


framework and provide the basis for event
handling so it is important to acquire a solid
understanding of how they work and how they
can be used.
◼ Delegates are a feature of C# not found in Java.
Steps for Defining and Using Delegates

◼ Creating and using delegates involves four


steps:
1. Delegate Declaration
2. Delegate method definition
3. Delegate instantiation
4. Delegate invocation.

6
Delegate Declaration
◼ A delegate declaration is a type declaration and
takes the following form:-
❑ modifier delegate return-type delegate-name (parameters);
◼ modifier used with delegates are:- public, private, protected
etc...
❑ The same access modifiers that can be applied to classes apply
for delegates.
◼ delegate is the keyword that signifies that the declaration
represents a class type derived from [Link].
◼ Example:-
❑ public delegate int Compareitems(int a, int b);

7
Delegate Methods
◼ The methods whose references are encapsulated into a
delegate instances are known as delegate methods or
callable entities.
◼ The signature and return type of delegate methods must
exactly match the signature and return type of the
delegate.
◼ For example:
➢ public delegate int myDelegate (int a, int b);
❑ can encapsulate to the following methods.
✓ public int Sum(int a, int b)
{
return a + b;
}

8
Delegate Instantiation

◼ Delegate declaration
➢ public delegate int myDelegate (int a, int b);

◼ Delegate method
➢ public static int Sum(int a, int b)
{
return a + b;
}

◼ Delegate instantiation
➢ myDelegate dg1 = new myDelegate(Sum);

9
Delegate Invocation
◼ When a delegate is invoked, it in turn invokes
the method whose reference has been
encapsulated into the delegate.
❑ delegate_object(parameters list);
◼ for example:-
❑ delegate1(x,y);
❑ int result=delegate(4 , 5);

10
Types of Delegates

1) Single Cast Delegates.

2) Multi Cast Delegates.

11
[Link] Cast Delegate
◼ A single cast delegate holds the reference of
only single method.
◼ Single-Cast Delegates: Derived Directly From
[Link]
❑ Invocation list contains only one method
Example: Single cast delegate
using System;
using [Link];
using [Link];
using [Link];
using [Link];

namespace Delegats_First_Program
{
// 1. Declaration
public delegate int myDelegate (int a, int b);

class testDelegate
{
// methods to be assigned and called by delegate
public int Sum(int a, int b)
{
return a + b;
}
public int Difference(int a, int b)
{
return a - b;
}
}
class Program
{
static void Main(string[] args)
{
testDelegate test1 = new testDelegate();

// 2. Instantiation : As a single cast delegate


myDelegate dg1 = new myDelegate([Link]);
myDelegate dg2 = new myDelegate([Link]);

// [Link]
[Link]("the sum of the numbers is:" + dg1(10, 20));
[Link]("the defrences is:" + dg2(20,10));
[Link]();
}
}
}
Output

❑ Sum of two integer is = 30


❑ Difference is = 10
2. Multicast Delegate
◼ Multicast delegate can be used to invoke the
multiple methods.
◼ Multicast Delegates: Derived from
[Link]
◼ Invocation list may contain multiple methods
◼ All methods will invoke in sequence as they are
assigned.
◼ Also known as combinable delegates.
◼ The return type must be void

15
Example: Multi cast delegate
using System;
using [Link];
namespace Delegates_Multicast
{
//1- Declaration
public delegate void multiCastDelegat(int a, int b);

class test
{
public void Sum(int a, int b)
{
[Link]("Sum of the two integers is:" + (a + b));
}

public void Diferrence(int a, int b)


{
[Link]("Diferences of the two integers is:"+ (a-b));
}
}
class Program
{
static void Main(string[] args)
{
test t1 = new test();
//[Link]
multiCastDelegat mutlidel = new multiCastDelegat([Link]);
mutlidel += new multiCastDelegat([Link]);

//3. Invocation
mutlidel(50, 20);

[Link]();
}
}
}
Output

❑ Sum of two integer is = 70


❑ Difference of two integer is = 30
Anonymous Method & Lambda Expressions

◼ Sometimes the whole signature of a method can be


more code than the body of a method.
◼ There are also situations in which you need to
create an entire method only to use it in a delegate.
◼ For these cases, Microsoft added some new
features to C#, 2.0 anonymous methods were
added.
◼ In C# 3.0, things became even better when lambda
expressions were added. Lambda expression is the
preferred way to go when writing new code.

18
Example: Anonymous Delegates (Anonymous Method)

using System;
namespace Delegates
{
class Program
{
// Delegate Definition
delegate void operation();

static void Main(string[] args)


{
// Delegate instantiation
operation obj = delegate
{
[Link]("Anonymous method");
};
obj();

[Link]();
}
}
}

19
Lambda Expression

◼ The lambda function has no specific name as


the methods.
◼ Because of this, lambda functions are called
anonymous functions.
◼ You also don’t have to specify a return type
explicitly.
❑ The compiler infers this automatically from your
lambda.

20
Example: Lambda Expression
using System;

namespace MathApp
{
class Program
{
public delegate void MathDelegate();

public static void Main()


{
MathDelegate md= new MathDelegate (()=> [Link]("Work1 Done!"));
md();

[Link]();
}
}
}

21
Key Points about Delegates
1. Delegates are like C++ function pointers but are type
safe.
2. Delegates allow methods to be passed as
parameters.
3. Delegates are used in event handling for defining
callback methods.
4. Delegates can be chained together i.e. these allow
defining a set of methods that executed as a single
unit.
5. Once a delegate is created, the method it is
associated will never changes because delegates are
unchallengeable in nature.
Key Points about Delegates 2…
6. Delegates provide a way to execute methods at
run-time.
7. All delegates are implicitly derived from
[Link], class which is inheriting
from [Link] class.
8. Delegates support calling of both static and
instance methods.

23

You might also like