Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C# Data Types
  • C# Decision Making
  • C# Methods
  • C# Delegates
  • C# Constructors
  • C# Arrays
  • C# ArrayList
  • C# String
  • C# Tuple
  • C# Indexers
  • C# Interface
  • C# Multithreading
  • C# Exception
Open In App
Next Article:
C# Func Delegate
Next article icon

C# Delegates

Last Updated : 11 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A delegate is an object which refers to a method or you can say it is a reference type variable that can hold a reference to the methods. It provides a way which tells which method is to be called when an event is triggered. 

For example, if you click on a Button on a form (Windows Form application), the program would call a specific method. In simple words, it is a type that represents references to methods with a particular parameter list and return type and then calls the method in a program for execution when it is needed.

Declaration of Delegates

Delegate type can be declared using the delegate keyword. Once a delegate is declared, delegate instance will refer and call those methods whose return type and parameter-list matches with the delegate declaration.

Syntax:  

[modifier] delegate [return_type] [delegate_name] ([parameter_list]);
  • modifier: It is the required modifier which defines the access of delegate and it is optional to use.
  • delegate: It is the keyword which is used to define the delegate.
  • return_type: It is the type of value returned by the methods which the delegate will be going to call. It can be void. A method must have the same return type as the delegate.
  • delegate_name: It is the user-defined name or identifier for the delegate.
  • parameter_list: This contains the parameters which are required by the method when called through the delegate. 


Example: 

// “public” is the modifier
// “int” is return type
// “GeeksForGeeks” is delegate name
// “(int G, int F, int G)” are the parameters
public delegate int GeeksForGeeks(int G, int F, int G);

Note: A delegate will call only a method which agrees with its signature and return type. A method can be a static method associated with a class or can be an instance method associated with an object, it doesn’t matter. 

Instantiation & Invocation of Delegates

After declaring a delegate, a delegate object is created with the help of new keyword. Once a delegate is instantiated, a method call made to the delegate is pass by the delegate to that method. The parameters passed to the delegate by the caller are passed to the method, and the return value, if any, from the method, is returned to the caller by the delegate. This is known as invoking the delegate. 

Syntax: 

[delegate_name]  [instance_name] = new [delegate_name](calling_method_name);

Example: 

CSharp
// Using of Delegates using System;  class Geeks  {     // Declaring the delegates     // Here return type and parameter type should      // be same as the return type and parameter type     // of the two methods     // "addnum" and "subnum" are two delegate names     public delegate void addnum(int a, int b);     public delegate void subnum(int a, int b);      public void sum(int a, int b)     {         Console.WriteLine("(100 + 40) = {0}", a + b);     }      public void subtract(int a, int b)     {         Console.WriteLine("(100 - 60) = {0}", a - b);     }      // Main Method     public static void Main(String []args)     {         // creating object "obj" of class "Geeks"         Geeks obj = new Geeks();          // creating object of delegate, name as "del_obj1"          // for method "sum" and "del_obj2" for method "subtract" &         // pass the parameter as the two methods by class object "obj"         // instantiating the delegates         addnum del_obj1 = new addnum(obj.sum);         subnum del_obj2 = new subnum(obj.subtract);          // pass the values to the methods by delegate object         del_obj1(100, 40);         del_obj2(100, 60);          // These can be written as using         // "Invoke" method         // del_obj1.Invoke(100, 40);         // del_obj2.Invoke(100, 60);     } } 

Output: 

(100 + 40) = 140
(100 - 60) = 40

Explanation: In the above program, there are two delegates addnum and subnum. We are creating the object obj of the class Geeks because both the methods(addnum and subnum) are instance methods. So they need an object to call. If methods are static then there is no need to create the object of the class.

Multicasting of a Delegate

Multicasting of delegate is an extension of the normal delegate(sometimes termed as Single Cast Delegate). It helps the user to point more than one method in a single call.

Properties: 

  • Delegates are combined and when you call a delegate then a complete list of methods is called.
  • All methods are called in First in First Out(FIFO) order.
  • ‘+’ or ‘+=’ Operator is used to add the methods to delegates.
  • ‘–’ or ‘-=’ Operator is used to remove the methods from the delegates list.

Note: Remember, multicasting of delegate should have a return type of Void otherwise it will throw a runtime exception. Also, the multicasting of delegate will return the value only from the last method added in the multicast. Although, the other methods will be executed successfully.

Below program demonstrates the use of Multicasting of a delegate: 

CSharp
// C# program to illustrate the  // Multicasting of Delegates using System;  class rectangle {      // declaring delegate public delegate void rectDelegate(double height,                                   double width);      // "area" method     public void area(double height, double width)     {         Console.WriteLine("Area is: {0}", (width * height));     }       // "perimeter" method     public void perimeter(double height, double width)     {         Console.WriteLine("Perimeter is: {0} ", 2 * (width + height));     }     // Main Method public static void Main(String []args) {          // creating object of class      // "rectangle", named as "rect"     rectangle rect = new rectangle();      // these two lines are normal calling     // of that two methods     // rect.area(6.3, 4.2);     // rect.perimeter(6.3, 4.2);      // creating delegate object, name as "rectdele"     // and pass the method as parameter by      // class object "rect"     rectDelegate rectdele = new rectDelegate(rect.area);          // also can be written as      // rectDelegate rectdele = rect.area;      // call 2nd method "perimeter"     // Multicasting     rectdele += rect.perimeter;       // pass the values in two method      // by using "Invoke" method     rectdele.Invoke(6.3, 4.2);     Console.WriteLine();          // call the methods with      // different values     rectdele.Invoke(16.3, 10.3); } } 

Output: 

Area is: 26.46
Perimeter is: 21

Area is: 167.89
Perimeter is: 53.2

Important Points About Delegates: 

  • Provides a good way to encapsulate the methods.
  • Delegates are the library class in System namespace.
  • These are the type-safe pointer of any method.
  • Delegates are mainly used in implementing the call-back methods and events.
  • Delegates can be chained together as two or more methods can be called on a single event.
  • It doesn’t care about the class of the object that it references.
  • Delegates can also be used in “anonymous methods” invocation.
  • Anonymous Methods(C# 2.0) and Lambda expressions(C# 3.0) are compiled to delegate types in certain contexts. Sometimes, these features together are known as anonymous functions.


Next Article
C# Func Delegate

S

SoumikMondal
Improve
Article Tags :
  • C#
  • CSharp-Delegates

Similar Reads

  • C# Func Delegate
    In C#, a delegate is a type that references a method. When creating a custom delegate, we follow these steps: Declare a delegate with a signature matching the target method.Create an instance of the delegate.Invoke the method using the delegate.But defining custom delegates manually can be repetitiv
    3 min read
  • C# Action Delegate
    Action delegate in C# is a built-in generic delegate type provided by the .NET framework. It is defined under the System namespace and is used to represent methods that do not return a value i.e. methods with a void return type. The Action delegate can accept from 0 to 16 input parameters of any typ
    3 min read
  • C# Predicate Delegate
    A Predicate delegate is an in-built generic type delegate. This delegate is defined under System namespace. It works with those methods which contain some set of criteria and determine whether the passed parameter fulfill the given criteria or not. This delegate takes only one input and returns the
    2 min read
  • Multicast Delegates in C#
    A type-safe function pointer is a delegate. It means that the delegate contains a reference to a method or function, and that when we invoke the delegate, the method to which it refers will be executed. The delegate signature and the method to which it points must both be signed. The method must be
    3 min read
  • Delegates vs Interfaces in C#
    A Delegate is an object which refers to a method or you can say it is a reference type variable that can hold a reference to the methods. Delegates in C# are similar to the function pointer in C/C++. It provides a way which tells which method is to be called when an event is triggered. Example: C/C+
    3 min read
  • C# Task Class
    The Task class is part of the Task Parallel Library (TPL) in System.Threading.Tasks. Introduced in .NET Framework 4.0, it provides a higher-level abstraction for asynchronous programming and parallelism. It allows operations to run in the background or in parallel with other tasks without blocking t
    10 min read
  • C# | Namespaces
    Namespaces are used to organize the classes. It helps to control the scope of methods and classes in larger .Net programming projects. In simpler words you can say that it provides a way to keep one set of names(like class names) different from other sets of names. The biggest advantage of using nam
    5 min read
  • C# Methods
    A method is a block of code that performs a specific task. It can be executed when called, and it may take inputs, process them, and return a result. Methods can be defined within classes and are used to break down complex programs into simpler, modular pieces. Methods improve code organization, rea
    4 min read
  • C# Thread Class
    In C#, multi-threading is implemented using the Thread class, which is part of the System.Threading namespace. This class allows for the creation, management, and control of threads within an application. The Thread class provides various methods and properties to handle thread execution, prioritize
    7 min read
  • C# Comments
    Comments are an essential part of the code. They allow developers to explain their code, document important information, and make the code easier to understand. Whatever you write in comments Compilers ignore it and do not execute them. In C#, There are three types of comments which are defined belo
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences