0% found this document useful (0 votes)
49 views2 pages

Declaring Delegates:: Code Example

The document discusses delegate declaration in C# and how a delegate determines the methods that can be referenced based on the signature. It provides an example of a delegate that can reference methods with a string parameter returning an int. The code example demonstrates creating delegate instances to call methods that add or multiply a number.

Uploaded by

Waleed Rana
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)
49 views2 pages

Declaring Delegates:: Code Example

The document discusses delegate declaration in C# and how a delegate determines the methods that can be referenced based on the signature. It provides an example of a delegate that can reference methods with a string parameter returning an int. The code example demonstrates creating delegate instances to call methods that add or multiply a number.

Uploaded by

Waleed Rana
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/ 2

Declaring Delegates:

Delegate declaration determines the methods that can be referenced by the


delegate. A delegate can refer to a method, which has the same signature as
that of the delegate.

For example, consider a delegate −


public delegate int MyDelegate (string s);

The preceding delegate can be used to reference any method that has a
single string parameter and returns an int type variable.

Syntax for delegate declaration is −


delegate <return type> <delegate-name> <parameter list>

Code Example:
using System;

delegate int NumberChanger(int n);

namespace DelegateAppl {

class TestDelegate {

static int num = 10;

public static int AddNum(int p) {

num += p;

return num;

public static int MultNum(int q) {

num *= q;

return num;

}
public static int getNum() {

return num;

static void Main(string[] args) {

//create delegate instances

NumberChanger nc1 = new NumberChanger(AddNum);

NumberChanger nc2 = new NumberChanger(MultNum);

//calling the methods using the delegate objects

nc1(25);

Console.WriteLine("Value of Num: {0}", getNum());

nc2(5);

Console.WriteLine("Value of Num: {0}", getNum());

Console.ReadKey();

You might also like