Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Discover the top 5 tips for understanding .NET Interop
Search :       Advanced Search »
Home » C# Language » Delegates in C#

Delegates in C#

This article discusses the delegate type and how it can be used to point to methods in the application which can be invoked at later time. This article demonstrates also the delegate ability to multicast and delegate covariance.

Page Views : 220652
Downloads : 1587
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
DelegatesInCSharp.zip
 
 
Nevron Chart
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


A delegate is a type-safe object that can point to another method (or possibly multiple methods) in the application, which can be invoked at later time.

Delegates also can invoke methods Asynchronously.

A delegate type maintains three important pices of information :

  1. The name of the method on which it make calls.
  2. Any argument (if any) of this method.
  3. The return value (if any) of this method.

Defining a Delegate in C#

when you want to create a delegate in C# you make use of delegate keyword.

The name of your delegate can be whatever you desire. However, you must define the delegate to match the signature of the method it will point to. fo example the following delegate can point to any method taking two integers and returning an integer.

public delegate int DelegateName(int x, int y);

A Delegate Usage Example

namespace MyFirstDelegate

{

    //This delegate can point to any method,

    //taking two integers and returning an

    //integer.

    public delegate int MyDelegate(int x, int y);

    //This class contains methods that MyDelegate will point to.

    public class MyClass

    {

        public static int Add(int x, int y)

        {

            return x + y;

        }

        public static int Multiply(int x, int y)

        {

            return x * y;

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            //Create an Instance of MyDelegate

            //that points to MyClass.Add().

            MyDelegate del1 = new MyDelegate(MyClass.Add);

            //Invoke Add() method using the delegate.

            int addResult = del1(5, 5);

            Console.WriteLine("5 + 5 = {0}\n", addResult);

            //Create an Instance of MyDelegate

            //that points to MyClass.Multiply().

            MyDelegate del2 = new MyDelegate(MyClass.Multiply);

            //Invoke Multiply() method using the delegate.

            int multiplyResult = del2(5, 5);

            Console.WriteLine("5 X 5 = {0}", multiplyResult);

            Console.ReadLine();

        }

    }
}

Delegate ability to Multicast

Delegate's ability to multicast means that a delegate object can maintain a list of methods to call, rather than a single method
if you want to add a method to the invocation list of a delegate object , you simply make use of the overloaded += operator, and if you want to remove a method from the invocation list you make use of the overloaded operator -= .

Note: The Multicast delegate here contain methods that return void, if you want to create a multicast delegate with return type you will get the return type of the last method in the invocation list.


A Multicast Delegate Example

namespace MyMulticastDelegate

{

    //this delegate will be used to call more than one

    //method at once

    public delegate void MulticastDelegate(int x, int y);

    //This class contains methods that MyDelegate will point to.

    public class MyClass

    {

        public static void Add(int x, int y)

        {

            Console.WriteLine("You are in Add() Method");

            Console.WriteLine("{0} + {1} = {2}\n", x, y, x + y);

        }

        public static void Multiply(int x, int y)

        {

            Console.WriteLine("You are in Multiply() Method");

            Console.WriteLine("{0} X {1} = {2}", x, y, x * y);

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            //Create an Instance of MulticastDelegate

            //that points to MyClass.Add().

            MulticastDelegate del = new MulticastDelegate(MyClass.Add);

            //using the same instance of MulticastDelegate

            //to call MyClass.Multibly() by adding it to it's

            //invocation list.

            del += new MulticastDelegate(MyClass.Multiply);

            //Invoke Add() and  Multiply() methods using the delegate.

            //Note that these methods must have a void return vlue

            Console.WriteLine("****calling Add() and Multibly() Methods.****\n\n");

            del(5, 5);

 

            //removing the Add() method from the invocation list

            del -= new MulticastDelegate(MyClass.Add);

            Console.WriteLine("\n\n****Add() Method removed.****\n\n");

            //this will invoke the Multibly() method only.

            del(5, 5);

        }

    }

}

Delegate Covariance

Assume you are designing a delegate that can point to methods returning a custom class type:

//Define a delegate pointing to methods returning Employee types.

public delegate Employee EmployeeDelegate();

if you were to derive a new class from Employee Type named SalesEmployee and wish to create a delegate type that can point to methods returning this class type you would be required to define an entirely new delegate to do so

//a new  delegate pointing to methods returning SalesEmployee types.

public delegate SalesEmployee SalesEmployeeDelegate();

Example

namespace MyEmployeesDelegate

{

    //Define a delegate pointing to methods returning Employee types.

    public delegate Employee EmployeeDelegate();

    //a new  delegate pointing to methods returning SalesEmployee types.

    public delegate SalesEmployee SalesEmployeeDelegate();

    class Program

    {

        public static Employee GetEmployee()

        {

            return new Employee();

        }

        public static SalesEmployee GetSalesEmployee()

        {

            return new SalesEmployee();

        }

        static void Main(string[] args)

        {

            EmployeeDelegate empDel = new EmployeeDelegate(GetEmployee);

            Employee emp = empDel();

            SalesEmployeeDelegate salesEmpDel = new SalesEmployeeDelegate(GetSalesEmployee);

            SalesEmployee emp2 = salesEmpDel();

        }

    }

    public class Employee

    {

        protected string firstName;

        protected string lastName;

        protected int Age;

        public Employee()

        { }

        public Employee(string fName, string lName, int age)

        {

            this.firstName = fName;

            this.lastName = lName;

            this.Age = age;

        }

 

    }

    public class SalesEmployee : Employee

    {

        protected int salesNumber;

        public SalesEmployee()

        { }

        public SalesEmployee(string fName, string lName, int age, int sNumber): base(fName, lName, age)

        {

            this.salesNumber = sNumber;

        }

    }

}

It would be ideal to build a single delegate type that can point to methods returning either Employee or SelesEmployee types.
Covariance allows you to build a single delegate that can point to methods returning class types related by classical inheritance.

Delegate Covariance Example

namespace DelegateCovariance

{

    //Define a single delegate that may return an Employee

    // or SalesEmployee

    public delegate Employee EmployeeDelegate();

    class Program

    {

        public static Employee GetEmployee()

        {

            return new Employee();

        }

        public static SalesEmployee GetSalesEmployee()

        {

            return new SalesEmployee();

        }

        static void Main(string[] args)

        {

            EmployeeDelegate emp = new EmployeeDelegate(GetEmployee);

            Employee emp1 = emp();

            EmployeeDelegate empB = new EmployeeDelegate(GetSalesEmployee);

            //to obtain a derived type you must perform an explicit cast.

            SalesEmployee emp2 = (SalesEmployee)empB();

        }

    }

    public class Employee

    {

        protected string firstName;

        protected string lastName;

        protected int Age;

        public Employee()

        { }

        public Employee(string fName, string lName, int age)

        {

            this.firstName = fName;

            this.lastName = lName;

            this.Age = age;

        }

    }

    public class SalesEmployee : Employee

    {

        protected int salesNumber;

        public SalesEmployee()

        { }

        public SalesEmployee(string fName, string lName, int age, int sNumber): base(fName, lName, age)

        {

            this.salesNumber = sNumber;

        }

    }

}

I hope you are now have a good idea with the creation and usage of delegates types.

Now you are ready to know about events in C#

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Amr Monjid
Amr Monjid is a computer programmer from Egypt. He has experience with C#, .Net framework, ASP.NET, Windows Applications, ADO.NET, Xml, Web Services, Custom Controls, and e-commerce web sites. and he is a MCTS: .NET framework 2.0, Windows Application, Distributed Aplication.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
Feedback by Mekala On January 20, 2009
Very useful article with good examples.
Reply | Email | Modify 
Re: Feedback by neha On March 6, 2011
http://www.totaldotnet.com/Article/ShowArticle57_Delegates.aspx
Reply | Email | Modify 
sdfsdf by naga On May 6, 2009

bcvbcvbcvb
bvcbbcvbcvbcvbcvbcvbcvbcvb

dsfsdfsdfsdfsdfsdfsdfsdf
sdfsdfsdfsdfsdfsdfsdfsdfsdfsdfsfsd

Reply | Email | Modify 
Very nice article for who is not having any idea about delegates by naga On May 6, 2009

Hi,

very thanks for posting such an nice article.It has been very helped for

knowing the delegates

Reply | Email | Modify 
Good by Aslam by Muhammed On January 10, 2010
Good and simple example for understanding Delegates quickly. Great work.
Reply | Email | Modify 
passing values by manjerekar_77 On January 28, 2010
how do i pass values to the parameterized constructor of the employee class.
Reply | Email | Modify 
Crystal clear. Thank You by Zeba On February 5, 2010

Reply | Email | Modify 
feedback for delegates by yamuna On May 21, 2010
Cute and informative description on delegate
Reply | Email | Modify 
Delegate by Bhupendra On May 31, 2010

Very concise and controled articall,Good Job.I want to read alll your articles.

Reply | Email | Modify 
Delegates in C# by purushothaman On July 29, 2010
"fo example the following delegate can point to any method taking two integers and returning an integer." Please check the spelling mistakes
Reply | Email | Modify 
Delegates in C# by Tribhuwan On August 20, 2010
very good
Reply | Email | Modify 
Very well explained by pritesh On August 31, 2010
Very well explained.tnx :)
Reply | Email | Modify 
Good Article by bhaskar On October 4, 2010
This is really helpful article.....Great work
Reply | Email | Modify 
comments by ahmed On October 18, 2010
its very helpfull artical
Reply | Email | Modify 
very good example u have taken by vishnu On October 27, 2010
really easy to understand....
nice article....
Reply | Email | Modify 
Feedback by vishal On December 23, 2010
Hi dude. You have written it with great simplicity. Now I have understood it properly, Thanks to you
Reply | Email | Modify 
hi by Hemanth On December 24, 2010
gr8 job.. tnx
Reply | Email | Modify 
HI by suriya On January 23, 2011
Thanks
Reply | Email | Modify 
Delegates by priyanka On February 19, 2011
That's good for the beginner's.
Reply | Email | Modify 
delegetes by muthu On February 19, 2011
simple and neat explanation
Reply | Email | Modify 
multicast delegate by senthil On March 29, 2011
Well. i have two methods which are similar to their signature and return type while i try to call both methods using delegates it always call second method only, how could i solve this problem?
Reply | Email | Modify 
Very nice Explanation by Mohamad On April 30, 2011
many thanks dear for the nice explanation... bless u
Reply | Email | Modify 
good one by BIJURAJ On May 5, 2011
very much helped....simple and good example
Reply | Email | Modify 
A quoi servent les délégués ? by Herve On May 12, 2011
Je débute en C# et j'ai du mal avec le concept des délégués. Avec le premier exemple de ce post on aurait eu le même résultat avec le code suivant: Myclass a = new Myclass; int addResult = a.Add(5, 5); Qu'apporte l'utilisation d'un délégué ? J'ai vraiment du mal à comprendre quand et pourquoi utiliser les délégués. Par avance merci de vos réponses...
Reply | Email | Modify 
Hi by venkat On June 25, 2011
delegate is a technique to pass the parameter to the funcation ...is it right?
Reply | Email | Modify 
Re: Hi by neha On June 26, 2011
A delegate is like a reference to a method. Once a delegate object, encapsulate a reference to a method inside it, the delegate can be called like the method, with same parameters and return-Type. Similar to function pointer in C or C++, A delegate in C# is used as reference to a method. To know more abt delegate http://www.totaldotnet.com/CSharp/CSharpEventDelegates.aspx
Reply | Email | Modify 
Delegate... by Deepan On July 7, 2011
In this article Delegate is clearly meantioned and also the example program..... thank you so much for the technical boost.......
Reply | Email | Modify 
Feedback by Annam On December 2, 2011
Hi Amr, Thanks for your clear explanation,it is really useful now i got some idea, about "+=" Operator, and please tell that when we have to use delegates,(when we have to add those methods to a list), I m a fresher.. thanks
Reply | Email | Modify 
Thanks for info by John On January 23, 2012
great article for delegates in C# http://www.4microsoftsolutions.com/post/Delegates-Multi-Cast-Delegates-in-C.aspx
Reply | Email | Modify 
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.