Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How and When To Use Delegates in Your Project

DZone's Guide to

How and When To Use Delegates in Your Project

In this tutorial, we'll take a step-by-step look at what exactly delegates do, how to create them, and how to use delegates in C# programs.

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

In this article, I will explain delegates, type of delegates, and when to use delegates.

After reading this article, you will learn the following:

  • What a delegate is. 
  • Where to use delegates.
  • Types of delegates.
  • When to use delegates.

What is a Delegate?

A delegate is similar to a function pointer in C and C++, but the delegates are user defined types in C#. Make a note that delegates are not a member of a class, but similar to a class. These are the backbones for events.

When Do You Use Delegates?

I believe that a lot of people can answer the "what is a delegate?" question in interviews, but are not able to explain when to use it. No worries! Let me tell you a few important points about delegates.

  1. These are used to represent or refer to one or more functions.
  2. These can only be used to define call-back methods.
  3. In order to consume a delegate, we need to create an object to delegate.

How Many Types of Delegates are Present?

There are two types of delegates available:

  1. Single Cast Delegate
  2. Multi Cast Delegate

Types of Delegates

A delegate that represents only a single function is known as a Single Cast Delegate. A delegate that represents more than one function is known as a Multi Cast Delegate. Before we dive into a sample program on these two types, I'd like to show the steps required to work with delegates.

  1. Creating a Delegate.
  2. Instantiating a Delegate.
  3. Invoking a Delegate.

Example:

Let us consider a function.

Public void Add(int a, int b) {
Code…..
}


In regards to the above function, if we want to use the delegate, we have to use the aforementioned three steps as shown below:

Step 1: Creating a Delegate

Syntax: Access modifier delegate return type Delegate name ([arguments list]);

Public delegate void Delegate (int x, int y); 


When we create a delegate, Access modifier, return type, number of arguments, and their data, the types of the delegate must and should be the same as Access modifier, return type, the number of arguments and the data types of the function that we want to refer to.

Step 2: Instantiating the Delegate

Syntax

Delegate name object name = new Delegate name (Targe Function name);

Example:

Delegate obj= new Delegate(Add);


What we are doing in this step is making a reference that will be maintained from the delegate object to the function that we want to refer to.

Step 3: Invoking the Delegate

Syntax

Object Name ([Arguments Values])

Example:

Obj(10,20)


At this step, the function that is referred to by the delegate will be called for the execution. So now, I hope you are clear about what delegates are, when to use delegates, and steps to work with delegates.

Now, let's start with a sample program on Single and Multiple delegates.

Single Cast Delegate

Let’s see a sample program on Single Delegate to refer a function in the same class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DelegatesDemo {
class Program {
static void Display(string S) {
Console.WriteLine("My Name is :" + S);
}
delegate void X(string a);
static void Main(string[] args) {
X objD = new X(Display);
objD("Rathrola Prem Kumar");
Console.Read();
}
}
}

Image title


Let's see another program for single cast delegate to refer a function in a different class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DelegatesDemo {
class Program {
public void Display(string S) {
Console.WriteLine("My Designation is :" + S);
}
public delegate void Delegate(string a);
class DelegateDemo {
static void Main() {
Program obj1 = new Program();
Delegate objD = new Delegate(obj1.Display);
objD("Technical Specialist");
Console.Read();
}
}
}
}

Image title


Sample Program for Multi Cast Delegate

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DelegatesDemo {
class Program {
public void Add(int x, int y) {
Console.WriteLine("Sum is:" + (x + y));
}
public void Subtract(int x, int y) {
Console.WriteLine("Difference is:" + (x - y));
}
public void Multiply(int x, int y) {
Console.WriteLine("Product is:" + (x * y));
}
public void Divide(int x, int y) {
Console.WriteLine("Quotient is:" + (x / y));
}
}
public delegate void MultiCastDelegate(int a, int b);
class ClsDelegate {
static void Main() {
Program obj1 = new Program();
MultiCastDelegate objD = new MultiCastDelegate(obj1.Multiply);
objD += obj1.Add;
objD += obj1.Substract;
objD += obj1.Divide;
objD(40, 10);
objD -= obj1.Add;
objD -= obj1.Divide;
objD(50, 10);
Console.ReadLine();
}
}
}

Image title

To add reference of more functions to a delegate object, we use += operator.

objD += obj1.substract;
objD += obj1.Add;

To delete the reference to any function from Delegate object, we use -= operator.

objD -= obj1.substract;
objD = -obj1.Add;

I hope, this article was helpful to you. Thanks for reading.

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:
c#.net ,C# ,webdev ,delegates

Published at DZone with permission of Rathrola Prem Kumar. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}