0% found this document useful (0 votes)
27 views

Delegates C#

1) A delegate in .NET allows assigning methods to be called later, like a function pointer in C#. 2) Delegates have three stages: declaration, instantiation assigning a method, and invocation calling the method. 3) Delegates are useful for dynamically created controls and multithreading.

Uploaded by

01fe18bcs028
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)
27 views

Delegates C#

1) A delegate in .NET allows assigning methods to be called later, like a function pointer in C#. 2) Delegates have three stages: declaration, instantiation assigning a method, and invocation calling the method. 3) Delegates are useful for dynamically created controls and multithreading.

Uploaded by

01fe18bcs028
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
You are on page 1/ 6

Delegates

Delegate's word meaning is representative. A delegate in .Net is juts like a function pointer in C#.

The most important property of a function pointer is that the syntax of the function and the pointer to the function

must exactly be same. The returntypes and the list of arguments must match exactly.

Eg: If a function looks like: int fact(int)

Then its function pointer should look like: int *p (int)


Here, as you may see the return types and the list of arguments of both function and function pointer match exactly.

When we use delegate then there are 3 stages which we need to follow:

1)Declaration:

delegate <returntype> delegateName (<list of arguments>)

2)Instantiation:

delegateName objDelegate = new delegateName(<function to which the delegate points>)

3)Invoking:

objDelegate(<list of arguments that are to be passed to the function>)

The main uses of delegate comes in the following circumstances:

1) When we want to create the controls dynamically, then we cannot create the events for these controls

beforehand as these controls are created only on runtime. In that case, if we want to bind these controls with

their respective events then we need to use delegate.

2) Delegate is also used in multitasking using threading.


1. Defining the delegate

public delegate int Calculate (int value1, int value2);

2. Creating the delegate object and assigning methods to those delegate objects

//creating the class which contains the methods


//that will be assigned to delegate objects
MyClass mc = new MyClass();

//creating delegate objects and assigning appropriate methods


//having the EXACT signature of the delegate
Calculate add = new Calculate(mc.add);
Calculate sub = new Calculate(mc.sub);

3. Invoking the methods via delegate objects

//using the delegate objects to call the assigned methods


Console.WriteLine("Adding two values: " + add(10, 6));
Console.WriteLine("Subtracting two values: " + sub(10,4));

When to Use Delegates Instead of Interfaces

Both delegates and interfaces allow a class designer to separate type declarations and implementation. A
given interface can be inherited and implemented by any class or struct; a delegate can created for a method
on any class, as long as the method fits the method signature for the delegate. An interface reference or a
delegate can be used by an object with no knowledge of the class that implements the interface or delegate
method. Given these similarities, when should a class designer use a delegate and when should they use an
interface?

Use a delegate when:

An eventing design pattern is used.

It is desirable to encapsulate a static method.


The caller has no need access other properties, methods, or interfaces on the object implementing the
method.
Easy composition is desired.
A class may need more than one implementation of the method.

Use an interface when:

There are a group of related methods that may be called.


A class only needs one implementation of the method.
The class using the interface will want to cast that interface to other interface or class types.
The method being implemented is linked to the type or identity of the class: for example, comparison
methods.

Example:1)

public delegate int BinaryOperation(int a,int b);


public class delegateTester
{
public int Add(int x,int y)
{
Console.WriteLine(x+y);
return(x+y);
}
public int Sub(int x, int y)
{
Console.WriteLine(x * y);
return (x*y);
}
}
public class Test{

public static void Main(string[] args)


{
delegateTester dt=new delegateTester();
BinaryOperation bo=new BinaryOperation(dt.Add);

delegateTester dt1=new delegateTester();


BinaryOperation bo1=new BinaryOperation(dt.Sub);

bo(10,20);
bo1(30,2);
Console.ReadLine();
}
}

Output:
30
28
2)Program that demonstrates delegate type [C#]

using System;

class Program
{
delegate string UppercaseDelegate(string input);

static string UppercaseFirst(string input)


{
char[] buffer = input.ToCharArray();
buffer[0] = char.ToUpper(buffer[0]);
return new string(buffer);
}

static string UppercaseLast(string input)


{
char[] buffer = input.ToCharArray();
buffer[buffer.Length - 1] = char.ToUpper(buffer[buffer.Length - 1]);
return new string(buffer);
}

static string UppercaseAll(string input)


{
return input.ToUpper();
}

static void WriteOutput(string input, UppercaseDelegate del)


{
Console.WriteLine("Your string before: {0}", input);
Console.WriteLine("Your string after: {0}", del(input));
}

static void Main()


{
// Wrap the methods inside delegate instances and pass to the method.
WriteOutput("Csharp", new UppercaseDelegate(UppercaseFirst));
WriteOutput("Csharp", new UppercaseDelegate(UppercaseLast));
WriteOutput("Csharp", new UppercaseDelegate(UppercaseAll));
}
}

Multicasting:

Multicasting is the ability to create an invocation list, or chain, of methods that will be automatically called when

a delegate is invoked. Such a chain can be created by instantiating a delegate and then use the + or +=

operator to add methods to the chain. To remove a method, use –or -=. If the delegate returns a value then the
value returned by last delegate in the list becomes the return value of the entire delegate invocation. Thus a

delegate that makes use of multicasting will often have a void return type.
Example 1 :

public delegate void MulticastDel();

public class delegateTester


{

public void method1()


{
Console.WriteLine(“This Is method 1”);
}
public void method2()
{
Console.WriteLine(“This is method 2”);
}
}
public class Test{

public static void Main(string[] args)


{
delegateTester d1= new delegateTester();
delegateTester d2= new delegateTester();

MulticastDel mo=new MulticastDel (d1. method1);


MulticastDel mo1=new MulticastDel (d2. method2);
MulticastDel mo3 = mo + mo1; //Multicasting
MulticastDel mo4 = mo3 - mo1;
mo3();
mo4();
Console.ReadLine();
}
}

Output:

This Is method 1
This is method 2
This Is method 1

Example 2:
class Rooster {
internal void Crow(){
Console.WriteLine("Cock-a-doodle-doo");
}
}
class PaperBoy {
internal void DeliverPapers(){
Console.WriteLine("Throw paper on roof");
}
}
class Sun {
internal void Rise(){
Console.WriteLine("Spread rosy fingers");
}
}
class DawnRoutine
{
delegate void DawnBehavior();
DawnBehavior multicast;
DawnRoutine()
{
multicast = new DawnBehavior(new Rooster().Crow);
multicast += new DawnBehavior(
new PaperBoy().DeliverPapers);
multicast += new DawnBehavior(new Sun().Rise);
}
void Break(){
multicast();

}
public static void Main()
{
DawnRoutine dr = new DawnRoutine();
dr.Break();
Console.ReadLine();
}
}
}
Output:

Cock-a-doodle-doo
Throw paper on roof
Spread rosy fingers

You might also like