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 » Visual C# » Simple and Multicast Delegates in C#.net

Simple and Multicast Delegates in C#.net

This article describes how to define and use simple/multicast delegates in C#.

Page Views : 66397
Downloads : 0
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

In C#, delegates represent methods that are callable without knowledge of the target object. Delegates enable scenarios that some other languages have addressed with function pointers. However, unlike function pointers, delegates are object-oriented and type-safe.

 

There are three steps in defining and using delegates: declaration, instantiation, and invocation.

 

Delegate Declaration:

 

public class DeligateClass

{

    public DeligateClass()

    {

    }

   
    // Declare a delegate

    public delegate void MessageHandler(string message);

    // The use of the delegate.

    public void Process(MessageHandler handler)

    {

        if (handler != null)

            handler("Begin Message");

        if (handler != null)

            handler("End Message");

    }

}

Function Class:

 

This class contains the functions will be called by delegates

 

public class FunctionClass

{

    public FunctionClass()

    {

    }

    //This method will show alert message to user

    public static void AlertMessage(string s)

    {

        System.Windows.Forms.MessageBox.Show(s);

    }

    //This method will write output to console

    public static void ConsoleMessage(string s)

    {

         Console.WriteLine(s);

     }

 } 

 

Instantiation and Invocation:

 

Client Application to use the defined Delegate

Simple Delegate

 

Create a windows form and add one button to it and paste the following code on its click event.

 

private void button1_Click(object sender, System.EventArgs e)

{

    //Instantiating a delegate

    DeligateClass dc = new DeligateClass();

    DeligateClass.MessageHandler ll = null;

    ll += new DeligateClass.MessageHandler(FunctionClass.AlertMessage);

 

    //Calling a delegate

    dc.Process(ll);

}

 

When you will click on button1, it will show 'Begin Message' and 'End Message' message box.

 

Multicast Delegate

 

Add one more button to form with following code.

 

private void button2_Click(object sender, System.EventArgs e)

{

    DeligateClass dc = new DeligateClass();

    DeligateClass.MessageHandler ll = null;

    ll += new DeligateClass.MessageHandler(FunctionClass.AlertMessage);

    ll += new     

    DeligateClass.MessageHandler(FunctionClass.ConsoleMessage);

    dc.Process(ll);

}

When you will click on button2, in addition to 'Begin Message' and 'End Message' message box, it will also write to console of visual studio (VS).

 

Delegates and interfaces are similar in that they enable the separation of specification and implementation. Multiple independent authors can produce implementations that are compatible with an interface specification. Similarly, a delegate specifies the signature of a method, and authors can write methods that are compatible with the delegate specification. There are direction defined by Microsoft when to use delegate and when to use interface.

Delegates are ideally suited for use as events - notifications from one component to "listeners" about changes in that component. 

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
 
Anand Thakur

 

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:
Nevron Chart
Become a Sponsor
 Comments
Thanks Man by asad On October 5, 2009
Nice, easy to understand...... keep it up dude....
Regards
Adee
Reply | Email | Modify 
Thanks....................... by Alok On February 6, 2010
Its very userful ...................
It helps me in a very urgent situation
Reply | Email | Modify 
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.