How to combine a Delegate call

Akiii
Posted by Akiii under C# category on | Points: 40 | Views : 912
Hi,
First i declare two sample methods which are as follows :-


public static void Method1(string msg)
{
Console.WriteLine("Method1 : " + msg);
}

public static void Method2(string msg)
{
Console.WriteLine("Method2 : " + msg);
Console.ReadLine();
}


Then we declare a Delegate :-

public delegate void TestDelegate(string msg);


Now, we make an object of the delegate, pass two methods in the constructor of it :-


static void Main(string[] args)
{
TestDelegate td = new TestDelegate(Method1);
td("hello");
td = new TestDelegate(Method2);
td("hello");
}


The above will output you the following message :-

Method1 : hello
Method2 : hello


In the above, first "td" is garbage collected when we instantiate "td" with the second method reference with the new operator !


Now, if we add a plus sign in the second method reference instantiation, then what will happen ? Watch carefully :-


static void Main(string[] args)
{
//SomeMethod("hello");
TestDelegate td = new TestDelegate(SomeMethod1);
td("hello");
td += new TestDelegate(SomeMethod2);
td.Invoke("hello");
}


Here the output message will be :-


Method1 : hello
Method1 : hello
Method2 : hello


What exactly happened here !
In the second method instantiation, we added a plus sign which signifies that the first object that is,"td", is not garbage collected. By adding a plus sign in the next line, we added the reference of the second method instantiation with the first one. So, first object that is,"td", will call method1 and then the same object(which is not garbage collected) will contain the reference of both the first and second method and that will be called in one shot. (This is the beauty of a Delegate !)



I hope you won't have any problem in understanding the above scenario !


Thanks and Regards
Akiii

Comments or Responses

Posted by: T.Saravanan on: 2/20/2012 Level:Silver | Status: [Member] [MVP] | Points: 10
Hi Akiii,

Nice info. Continue your great effort in our DNF!!!
Posted by: Akiii on: 2/20/2012 Level:Bronze | Status: [Member] | Points: 10
Thanks Saravanan for your encouragement !


I hope to contribute more to DNF..

Regards
Akiii

Login to post response