Practical Use of Delegate in real time Application -1

Esensahoo
Posted by in C# category on for Intermediate level | Points: 250 | Views : 46586 red flag
Rating: 4.67 out of 5  
 3 vote(s)

This article describes how can we use a delegate in a real time application to build dynamic components. I will write this article in two phases and the first phase goes here.

Introduction

Many time we get questions like where can we use delegate ?  Give us a practical example .In fact I saw 2-3 similar questions in this forum so thought of writing this article.

In this age programmers are more interested in building dynamic and reusable component. There are scenarios where a normal function will not help to fulfil the purpose. Below are two important features in delegate which helps to make a component dynamic.

1-      1. It allows to inject code by the client(I will describe in this article)

2-      2. Multi-casting (I will describe in the next article)


Inject functions by client code.

Ok let's do a practical  example to make it clear. One important use of delegate is with the help of delegate  we can develop a component which client can use and inject their functionality to it. In the below example I have shown a UserRegistration Component. Client will call this component to register a user ,however it entirely depends on the client  to implement how they want to notify users about their registration via email or via SMS .

 

namespace RegistrationModule

{ 

    public delegate void NotifyUser(ContactDetail objContact); 

    class RegisterUser
    {

        public void Register(Userinfo objUser, NotifyUser myFunc)
        {

            //code to save the user details to the database

            // 

            myFunc(objUser.objContact);

        } 

    }

 

    class Userinfo
    {

        public string name;
        public int age;
        public ContactDetail objContact;
    }

    class ContactDetail
    {

        public string email;
        public string mobNo;
    }

}

 

Client Code:

Lets say first client wants to send SMS to notify their user.So below will be their implementation.

I have given the comment to explain the code.

//Below function is having same signature as delegate NotifyUser and will be attached to the delegate.
public void SendSMS(ContactDetail objContact)

        {

            string MobNo = objContact.mobNo;
            //Add your code to send Registration success message to the user mobile number.

        }

 

        public void RegisterUser()

        {
  //Create an Object of Userifo and fill the user details to it.
            Userinfo obj = new Userinfo();           

            obj.name = "Satya Sahoo";

            obj.age = 29;

            ContactDetail objC = new ContactDetail();

            objC.mobNo = "977788888";

            objC.email = "esensahoo@sweetcrazyboy.net";

            obj.objContact = objC;

   //Create a delegate instance and attach the SendSMS() to it.
            NotifyUser sendSMS = new NotifyUser(SendSMS);

            RegisterUser objReg = new RegisterUser();

//Invoke the register function with the Delegate Instance sendSMS


            objReg.Register(obj, sendSMS); 

        }

 

Now lets say the second client wants to notify the user via email:

public void SendEmail(ContactDetail objContact)

        {
            string strEmail = objContact. email;

            //Add your code to send Registration success email to the user email address.

        }

 

        public void RegisterUser()

        {

            Userinfo obj = new Userinfo();           

            obj.name = "Satya Sahoo";

            obj.age = 29;

            ContactDetail objC = new ContactDetail();

            objC.mobNo = "977788888";

            objC.email = "esensahoo@sweetcrazyboy.net";

            obj.objContact = objC; 

            NotifyUser sendEmail = new NotifyUser(SendEmail); 

            RegisterUser objReg = new RegisterUser();

            objReg.Register(obj, sendEmail);

         }

That's it.Now client-1 user will get user registration success message as an SMS and client-2 will get user registration success message as an email.  Important thing to notice here is SendSMS and SendEmail is the code written by the client however it is invoked by the RegistrationModule what in other words we can say delegates allow us to inject functionality.


Conclusion

I hope this will helps to give a practical use of delegate.In the next article I will give a practical implementation of multicasting.Please feel free to email me in case you have any question on the same. 
Page copy protected against web site content infringement by Copyscape

About the Author

Esensahoo
Full Name: SATYA SAHOO
Member Level: Starter
Member Status: Member
Member Since: 12/28/2010 8:47:18 AM
Country: India


Working in Misys Software solution having interest in learning and writing on MS.Net technologies.

Login to vote for this post.

Comments or Responses

Posted by: Mauryavijai on: 1/3/2011 | Points: 25
Very Nice Article Satya...
Posted by: Karthikanbarasan on: 1/3/2011 | Points: 25
Good article to start with delegate...

Posted by: Sdudhatra on: 1/11/2011 | Points: 25
Very practical example... I will sure try to use in similar fashion if need arise..

Posted by: Gayathri on: 7/22/2011 | Points: 25
Hi Satya,
thanks for an excellent article. but kindly excuse me. i have few doubts in this.
as i am not so good in C# ,the following question may sound you very silly.

1) public void Register(Userinfo objUser, NotifyUser myFunc)
{
//code to save the user details to the database
//
myFunc(objUser.objContact); -- > should not you use new here? if so why? to me normally we create a delegate instance as <delegatename> <variable name> = new <delegatename(methodname)>;
please clarify.

Thanks
-Gayathri
Posted by: Esensahoo on: 7/22/2011 | Points: 25
Hi Gayathri,

You are right , we initialize the delegate using
<delegatename> <variable name> = new <delegatename(methodname)>
and the same is done in my client code sample,
NotifyUser sendEmail = new NotifyUser(SendEmail);

here
NotifyUser - <delegatename>
SendEmail/SendSMS - methodname

here client is expected to initialize the delegate ,so the delegate is intentionally left un-initialized or we can initialize with a default blank implantation for the delegate.

Please feel free to post doubts in case you have any.

Thanks,
Satya N. Sahoo


Posted by: mohanchug-7980 on: 6/25/2012 | Points: 25
Hi Satya !
Was it not possible for the client to call sendSMS or SendEmail after calling the register user
here we also have the flexibility of checking if the ResterUser returned sucess or failure.

I am not sure how delegate helped us here?

Login to post response

Comment using Facebook(Author doesn't get notification)