using delegates and events in c#

. Thursday, April 7, 2011
  • Agregar a Technorati
  • Agregar a Del.icio.us
  • Agregar a DiggIt!
  • Agregar a Yahoo!
  • Agregar a Google
  • Agregar a Meneame
  • Agregar a Furl
  • Agregar a Reddit
  • Agregar a Magnolia
  • Agregar a Blinklist
  • Agregar a Blogmarks


What is a delegate ? 
Delegate is a function pointer means it can point to those function which are having identical signature with delegate.
you can also call delegate as a interface of methods as this acts same as interface in c# but that implemented for classes and this is implemented for methods.

Process to create a delegate:
1)declaration
2)instantiation
3)invocation

Example :

Consider the following code:

  delegate string StrDelegate();//declaration
   public class Custom
    {
        public string strmethod()
        {
            return "This is string ";
        }
    }
    class Program
        {
        static void Main(string[] args)
        {
            Custom objcustom = new Custom();
            StrDelegate strdelegate = new  StrDelegate(objcustom.strmethod); //instantiation
            string message=strdelegate(); //invocation
            Console.Write(message);
            Console.Read();
        }
       }
so what happened in this above code,well first we define a delegate with its signature,in this case its return type is string and no arguments. then we create instance of delegate which is strdelegate now this can point to (reference to) all those function which having same signature as in our case function is strmethod() and at the last we invoke this and receive this in message.

Advantages:
The main advantage of delegate is multi cast.
you can call number of function with matching singature with single instance of delegate but point to remember is that its return type should be void because there are many

methods and if we pass return type then each one will return some value and finally delegate instance will hold the last one method's value.

example

in our previous example i added the following :

        public void strmethodmulticast()
        {
           console.write("This is string multicast");

        }

in set of methods and

StrDelegate strdelegate = null;
            strdelegate += new StrDelegate(objcustom.strmethod);
            strdelegate += new StrDelegate(objcustom.strmethodmulticast);

this in Static Void Main

also changed the return type of delegate to void.


What are events 
event is a way for a class to provide notifications to clients of that class when some interesting thing happens to an object of that class.
you can also consider events as variable type of delegates ? why lets look at event declaration.

public event StrDelegate customevent;

Just need to put event keyword before delegate name and your event created.
events are handled by delegates which are called event handlers.

consider the following code:

 btnsubmit.Click+=new EventHandler(custommethod);

I created a button on form and its object 'btnsubmit' now avaiable on code behind as you know, now when click event raises in above it is being handled by EventHandler
delegate and method  'custommethod'  do the desire operation which is having the same signature as in EventHandler delegate (object sender//to raise event,Eventargs e// to receive other information)

public void custommethod(object sender, EventArgs e)
    {
        txtsubmit.Text = "This is called on button click";

    }

and hence on click event of button the above method is called which changes the text of txtsubmit.

3 comments:

Hassan said...

hi vishal , am not able to understand the purpose of declaring an event delegate mentioned below , could you please explain why you have declared it ?

public event StrDelegate customevent;

vishal patwardhan said...

Purpose of declaring strDelegate is to show how can you create your custom event by just typing event keyword,let look below code for how can create and call your own custom event.

class Product
{
//declare delegate.
public delegate void ProductEventHandler(object sender, ProductEventArgs pr);

//declare event.
public event ProductEventHandler ProductEvent;

//function which will raise the event.
public void RaiseEvent()
{
//pass some value to event args class.
ProductEventArgs pr = new ProductEventArgs("This is Custom Message");

//event call
ProductEvent(this, pr);
}

}
//event argument class inherited from system.eventargs.
class ProductEventArgs : System.EventArgs
{
public string Message;
public ProductEventArgs(string message)
{
this.Message = message;
}
public string GetMessage()
{
return Message;
}
}



class Program
{
static void Main(string[] args)
{
Product objproduct = new Product();
//fire the event
objproduct.ProductEvent+=new Product.ProductEventHandler(ProductEventCall);

//raise the event by calling function of Product class
objproduct.RaiseEvent();
}

//function which will be called when event is fired.
public static void ProductEventCall(object sender, ProductEventArgs args)
{

Console.Write(args.GetMessage());
Console.Read();
}
}

Anonymous said...

Good and concise review! TnX!