Monday, February 22, 2010

Delegates Inside




Delegates are one of most complex and simplest concept in .Net ;) .

Delegates in c# are defained as Function Pointers. Those functions can be an instance function or a static function. In case of instance function delegeate store the reference of that object in its property called "Target".

Once an instance function is added to a deletegate then that function will always be invoked by delegate event if you set instance to null................

Lets take an example :

using System;

static class Program
{
[STAThread]
static void Main()
{

EventHandelerClass handeler = new EventHandelerClass("My Text");
delShow showMe = new delShow(handeler.OnShow);
handeler.Text = "Changed ";
handeler = null;  // set to null 
GC.Collect(); // Make sure it is released 
Console.WriteLine(showMe(" From Delegate"));
Console.ReadLine();

}
}


public delegate String delShow(String msg);

public class EventHandelerClass
{
public String Text
{
get;
set;
}
public EventHandelerClass(string text)
{
Text = text;
}

public String OnShow(String msg)
{
return this.Text + msg;
}


}



Above program will display message "My Text From Delegate" even if handeler is set to null.

This is because when you add a instance method to a delegate it store reference of that instance in its "Target" property. When we set handeler = null actually we are saying now "handeler" will no longer point to the address but delegate "showMe" is still pointing to same address ( ref How reference types are stored ? ).

Whole idea is once we have assign a function pointer to a delegate or event it will always call it ; simply setting instance to null will not remove the handler. To remove handler we need to either use "-=" or "MulticastDelegate.Remove" method.

I faced this problem while implementing MVP in one of my project where I have disposed a consumer form but the event handler was still called. in my next article I will try to explain MVP implementation in detail.

5 comments:

Satyawan Singh said...

Nice Article and useful too. Even when handler is set to null then also the delegate function is getting called :). Should be asked in Interviews :)

Fakhrul Islam said...

Very helpful article, it's really great help for developer like me who are in search of this solution.

pradeep yadav said...

really very helpful. thanks

pradeep yadav said...

That's really helpful. thanks a lot.

Anonymous said...

Awesome!