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
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » C# Language » How to use Delegate?

How to use Delegate?

Most of us would know what is delegate. But many us of don't use them efficient enough. In this project, I have shown different methods to use delegates.

Page Views : 3678
Downloads : 59
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
Program.zip
 
 
DevExpress Free UI Controls
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


Most of us would know what is delegate. But many us of don't use them efficient enough. In this project, I have shown different methods to use delegates. This is extremely basic example for delegate. You can use these techniques and then can build up complex logics and architectures. It helps a lot for Interface supporting/driven application i.e. embedded systems.
 
Introduction: 
 
Delegate is a reference to one or more methods that can be called up by a single call. It is like a 'Function Pointer ' of 'C' Language. Delegate is method without code.
 
Code: I have made for classes delegatesExample1, delegatesExample2, delegatesExample3 and delegatesExample4 which is having start method.
 
1) Main thread
 
static void Main(string[] args)
{
    new delegatesExample1().Start();           
    new delegatesExample2().Start();
    new delegatesExample3().Start();
    new delegatesExample4().Start();
    Console.ReadKey();
}
 
Here, I have called start method of each example class. Now I'll be explaining each class one by one.
 
2) Example 1
 
class delegatesExample1
{
    delegate void MyMethod(String str);
    public delegatesExample1()
    {
        Console.WriteLine("Delegate Example 1 Starts");
    }
    public void Start()
    {
        MyMethod methodsToCall = null;
        methodsToCall += new MyMethod(reverseString);
        methodsToCall += new MyMethod(uppercaseString);
        methodsToCall("Nilay");
    }
    void reverseString(String str)
    {
        char[] arr = str.ToCharArray();
        Array.Reverse(arr);
        Console.WriteLine("Reverse: " + new string(arr));
    }
    void uppercaseString(String str)
    {
        Console.WriteLine("Uppercase: " + str.ToUpper());
    }
}   
 
In this class I have first defined delegate MyMethod accepting string.
 
Then in 'Start()' method, I'm attaching or binding methods to the delegate.
 
And then invoking that delegate instance which will subsequently call all the methods attached to that delegate. In this example method 'reverseString' and 'uppercaseString' will be called up.
 
3) Example 2
 
class delegatesExample2
{
    delegate void MyMethod(String str);
    event MyMethod MyMethodEvent = null;
    public delegatesExample2()
    {
        Console.WriteLine("\nDelegate Example 2 Starts");
    }
    public void Start()
    {
        MyMethodEvent += (reverseString);
        MyMethodEvent += (uppercaseString);
        MyMethodEvent("Nilay");
        //FOLLOWING CODE CAN ALSO BE USED
        //TO CALL ALL THE METHODS RELATED TO EVENT
        MyMethodEvent.Invoke("Joshi");
    }
    void reverseString(String str)
    {
        char[] arr = str.ToCharArray();
        Array.Reverse(arr);
        Console.WriteLine("Reverse: " + new string(arr));
    }
    void uppercaseString(String str)
    {
        Console.WriteLine("Uppercase: " + str.ToUpper());
    }
}
 
In previous example we have created delegate instance and we were directly invoking that instance.
 
But In this example I have created an event for my delegate. This is a common way to expose an event for custom controls. An instance of an event has been created and been invoked.
 
4) Example 3
 
class delegatesExample3
{
    delegate void MyMethod(String str);
    public delegatesExample3()
    {
        Console.WriteLine("\nDelegate Example 3 Starts");
    }
    public void Start()
    {
        extraProcessing(reverseString);
        extraProcessing2(uppercaseString, reverseString);
        extraProcessing3(delegate(String str)
        {
            Console.WriteLine("Method defined in function call:");
            Console.WriteLine(str);
        }
                 );
        MyMethod methodObj = null;
        methodObj += new MyMethod(reverseString);
        methodObj += new MyMethod(uppercaseString);
        extraProcessing3(methodObj);
    }
    void extraProcessing(MyMethod method1)
    {
        Console.WriteLine("Passed function as a parameter: ");
        method1("Nilay");
    }
    void extraProcessing2(MyMethod meth1, MyMethod meth2)
    {
        Console.WriteLine("Passed 2 Functions as a Parameter:");
        Console.WriteLine("1st Function:");
        meth1("Nilay");
        Console.WriteLine("2st Function:");
        meth2("Joshi");
    }
    void extraProcessing3(MyMethod method1)
    {
        method1("nj");
    }
    void reverseString(String str)
    {
        char[] arr = str.ToCharArray();
        Array.Reverse(arr);
        Console.WriteLine("Reverse: " + new string(arr));
    }
    void uppercaseString(String str)
    {
        Console.WriteLine("Uppercase: " + str.ToUpper());
    }
}
 
This is very interesting example. In this example delegate is passed as a parameter to the function.
 
In extraProcessing1 and extraProcessing2, I have passed method name directly.
 
In extaProcessing3, using delegate I defined Anonymous method and passed it as a parameter.
 
In last, againg I made instance of a delegate and attached two methods to that instance and passed that instance to the function.
 
5) Example 4
 
class delegatesExample4
{
    delegate String MyMethod(String str);       
    public delegatesExample4()
    {
        Console.WriteLine("\nDelegate Example 4 Starts");
    }
    public void Start()
    {
        CallMe(     delegate(string x)
                    {
                        return x.ToLower();
                    }
                );
    }
    void CallMe(MyMethod meth1)
    {
        Console.WriteLine("Hello " + meth1("Nilay"));
    }
}      
 
This example shows another use of a delegate returning value.
 
In this example, I have shown how to use delegate returning a value.
 
Closing Notes:
 
I hope this these examples have cleared basic idea of delegate. Please provide me your feedback about my article or any other suggestions.
 
Total Code:
 
class Program
{
    static void Main(string[] args)
    {
        new delegatesExample1().Start();           
        new delegatesExample2().Start();
        new delegatesExample3().Start();
        new delegatesExample4().Start();
        Console.ReadKey();
    }
}
    class delegatesExample1
    {
        delegate void MyMethod(String str);
        public delegatesExample1()
        {
            Console.WriteLine("Delegate Example 1 Starts");
        }
        public void Start()
        {
            MyMethod methodsToCall = null;
            methodsToCall += new MyMethod(reverseString);
            methodsToCall += new MyMethod(uppercaseString);
            methodsToCall("Nilay");
        }
        void reverseString(String str)
        {
            char[] arr = str.ToCharArray();
            Array.Reverse(arr);
            Console.WriteLine("Reverse: " + new string(arr));
        }
        void uppercaseString(String str)
        {
            Console.WriteLine("Uppercase: " + str.ToUpper());
        }
    }   
    class delegatesExample2
    {
        delegate void MyMethod(String str);
        event MyMethod MyMethodEvent = null;
        public delegatesExample2()
        {
            Console.WriteLine("\nDelegate Example 2 Starts");
        }
        public void Start()
        {
            MyMethodEvent += (reverseString);
            MyMethodEvent += (uppercaseString);
            MyMethodEvent("Nilay");
            //FOLLOWING CODE CAN ALSO BE USED
            //TO CALL ALL THE METHODS RELATED TO EVENT
            MyMethodEvent.Invoke("Joshi");
        }
        void reverseString(String str)
        {
            char[] arr = str.ToCharArray();
            Array.Reverse(arr);
            Console.WriteLine("Reverse: " + new string(arr));
        }
        void uppercaseString(String str)
        {
            Console.WriteLine("Uppercase: " + str.ToUpper());
        }
    }
    class delegatesExample3
    {
        delegate void MyMethod(String str);
        public delegatesExample3()
        {
            Console.WriteLine("\nDelegate Example 3 Starts");
        }
        public void Start()
        {
            extraProcessing(reverseString);
            extraProcessing2(uppercaseString, reverseString);
            extraProcessing3(delegate(String str)
            {
                Console.WriteLine("Method defined in function call:");
                Console.WriteLine(str);
            }
                            );
            MyMethod methodObj = null;
            methodObj += new MyMethod(reverseString);
            methodObj += new MyMethod(uppercaseString);
            extraProcessing3(methodObj);
        }
        void extraProcessing(MyMethod method1)
        {
            Console.WriteLine("Passed function as a parameter: ");
            method1("Nilay");
        }
        void extraProcessing2(MyMethod meth1, MyMethod meth2)
        {
            Console.WriteLine("Passed 2 Functions as a Parameter:");
            Console.WriteLine("1st Function:");
            meth1("Nilay");
            Console.WriteLine("2st Function:");
            meth2("Joshi");
        } 
        void extraProcessing3(MyMethod method1)
        {
            method1("nj");
        }
        void reverseString(String str)
        {
            char[] arr = str.ToCharArray();
            Array.Reverse(arr);
            Console.WriteLine("Reverse: " + new string(arr));
        }
        void uppercaseString(String str)
        {
            Console.WriteLine("Uppercase: " + str.ToUpper());
        }
    }
    class delegatesExample4
    {
        delegate String MyMethod(String str);       
        public delegatesExample4()
        {
            Console.WriteLine("\nDelegate Example 4 Starts");
        }
        public void Start()
        {
            CallMe(     delegate(string x)
                        {
                            return x.ToLower();
                        }
                    );
        }
        void CallMe(MyMethod meth1)
        {
            Console.WriteLine("Hello " + meth1("Nilay"));
        }
}    
 
Output: 
 
1.gif

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
 
Nilay Joshi
I have completed my Bachelors Degree in Computer Engineering and Currently working as a Software-Engineer.
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:
DevExpress Free UI Controls
Become a Sponsor
 Comments
6 Months Free & No Setup Fees ASP.NET Hosting!
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.