Delegates
A delegate defines the signature for a particular method (i.e. the parameter list and the return type).
Using delegates allow you to pass functions to and from other functions.
This delegate can then be used to refer to any object or variable with the same signature.
Delegates give you a way of calling methods which are only known at run time.
A delegate is a reference type that represents a method with a specific signature and return type.
These allow you to specify methods at run-time.
Assigning a method to a delegate creates a delegate instance.
Why are Delegates useful ?
Event Handlers are implemented as delegates.
A delegate can refer to a regular subroutine or function in a module.
A delegate can refer to a shared subroutine or function in a class.
A delegate can refer to an instance procedure.
All .NET events are internally implemented through delegates.
Defining a Delegate
Lets suppose that we have 2 subroutinse and we want to decide which one to use at run-time.
void DelegateMethod1(string sMessage) {
System.Console.WriteLine(sMessage);
}
void DelegateMethod2(string sMessage) {
System.Console.WriteLine(sMessage);
}
You must first declare a delegate with an identical signature.
This delegate can be used to refer to any method that accepts a String argument.
public delegate void Del_MyDelegate(string sMessage);
At run-time you can create an instance of this delegate passing in the corresponding method name.
Instantiate
Del_MyDelegate1 delMyDelegate;
delMyDelegate = DelegateMethod1;
Once the delegate has been created this method can then be used within your code.
Invoke is the default method.
delMyDelegate.Invoke("display this message");
delMyDelegate("display this message");
Example
Lets suppose you wanted to create a simple container class called Pair that can hold and sort any two objects passed to it.
You don't know in advance what kind of objects it will hold, but it is possible to create methods within those objects which the sorting task can be delegated to.
This problem is solved by delegating this responsibility to the objects themselves.
Our pair class no longer needs to know how the objects are sorted; it just needs to know that they can be sorted.
The pair container needs to specify the method these objects must implement.
Rather than specifying a particular method name, the pair needs to specify the signature and the return type.
(( you can call your delegate methods anything you like ))
Asynchronous Delegates
IAsyncResult
Shared Delegates
One disadvantage of using delegates is that the calling code must instantiate the delegates it needs before it can use the delegate.
Rather than forcing the code to know which methods to use it would be better to get the delegate from the actual object classes themselves.
You can give each object class the responsibility for instantiating the delegate by implementing its own shared delegate.
The problem with shared delegates is that they must always be instantiated regardless of whether they are used or not.
You must first declare a Delegate with an identical signature.
Public Delegate Function Del_AskQuestion(ByVal sMessage As String) As Boolean
Sub Main()
Dim delAskQuestion As Del_AskQuestion
delAskQuestion = New Del_AskQuestion(AddressOf MessageType.AskYesNo)
If delAskQuestion.Invoke("Do you want to save this file ?") = True Then
End If
End Sub
This class contains a shared function that returns True if the user answers Yes to the question.
Public Class MessageType
Public Shared Function AskYesNo(ByVal sMessage As String) As Boolean
Dim answer As objMsgBoxResult
objanswer = MsgBox(sMessage, MsgBoxStyle.YesNo Or MsgBoxStyle.Question)
AskYesNo = (objanswer = MsgBoxResult.Yes)
End Function
End Class
Multicast Delegates
A delegate that points to multiple methods is called a multicast delegate. The + operator adds a function to the delegate object and the - operator removes an existing function from a delegate object.
When the multicast delegate is called, it invokes the delegates in the list, in order. Only delegates of the same type can be combined.
namespace Delegates
{
delegate void ArithmeticOperation(double operand1, double operand2);
class Program
{
static void Addition(double number1, double number2)
{
System.Console.WriteLine($"{number1} + {number2} = {number1 + number2}");
}
static void Subtraction(double number1, double number2)
{
System.Console.WriteLine($"{number1} - {number2} = {number1 - number2}");
}
static void Multiplication(double number1, double number2)
{
System.Console.WriteLine($"{number1} * {number2} = {number1 * number2}");
}
static void Division(double number1, double number2)
{
System.Console.WriteLine($"{number1} / {number2} = {number1 / number2}");
}
static void Main(string[] args)
{
ArithmeticOperation operations = Addition;
operations += Subtraction;
operations += Multiplication;
operations += Division;
operations(10, 5);
System.Console.WriteLine();
}
}
}
Generic Delegates
Lambda Expressions
Added in .NET 3.5
A lambda expression is an unnamed method written in a place of a delegate instance.
You use a lambda expression to create an anonymous function.
Use the lambda declaration operator => to separate the lambda's parameter list from its body.
A lambda expression is an anonymous function that you can use to create delegates.
This lets you write local functions that can be passed as arguments or returned from functions.
A lambda expression is a block of code (an expression or a statement block) that is treated as an object. It can be passed as an argument to methods, and it can also be returned by method calls.
To create a lambda expression you specify the input parameters on the left of the lambda operator with an expression or statement block on the right
Multi-line lambda expressions were added to VB.Net in Visual Studio 2010.
string Person = peoplelist.Find(name => name.Contains("m")
instead of
public string FindPerson(string contains, List<string> peoplelist)
{
for each (string name in peoplelist)
{
if (name.Contains("m"))
{
return name;
}
}
return null;
}
System.Threading.Thread myThread;
myThread = new System.Threading.Thread( delegate() { Method_Print("one", "two"); });
void Method_Print(string name, string value)
{
}
Anonymous Methods
Added in .NET 2.0
These are superseded by Lambda Expressions
Anonymous methods allow you to define a delegate inline.
An anonymous method provides a way of passing a block of code as an argument instead of creating an explicit named method.
Use the delegate keyword to declare a delegate type first
A parameter is then passed to an anonymous method using the delegate keyword
no parameters
delegate void Delegate_Type();
Delegate_Type delegate_variable = delegate()
{ // do something }
instead of
delegate void Delegate_Type();
void Method_Name()
{ // do something }
Delegate_Type delegate_variable = Method_Name;
with a parameter
delegate int Delegate_Type(int x);
Delegate_Type delegate_variable = delegate(int paramater)
{ return paremeter * parameter; }
instead of
delegate int Delegate_Type(int x);
int Method_Name(int parameter)
{ return parameter * parameter; }
Delegate_Type delegate_variable = Method_Name;
© 2026 Better Solutions Limited. All Rights Reserved. © 2026 Better Solutions Limited TopPrev