DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Data Engineering
  3. Data
  4. How and When To Use Delegates in Your Project

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.

Rathrola Prem Kumar user avatar by
Rathrola Prem Kumar
·
Mar. 07, 17 · Tutorial
Like (1)
Save
Tweet
Share
7.28K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Object (computer science) Syntax (programming languages) Data (computing) Operator (extension) Execution (computing) c++ Pointer (computer programming) Clear (Unix) Event

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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Spring Cloud
  • Apache Kafka Is NOT Real Real-Time Data Streaming!
  • 10 Easy Steps To Start Using Git and GitHub
  • Cucumber.js Tutorial With Examples For Selenium JavaScript

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: