Monday, July 10, 2006

Delegates in .NET

After browsing many over complex delegate articles I think i have established their real use. Say you have a class A with a function DoWork(). At the end of the DoWork function you need a certain event to be triggered but this event could change at any given time whilst the app is open.

To solve this you would create a new instance of a delegate called mytask

public delegate void mytask();

then in your class A's Do Work function you pass in the delegate as a parameter

public void DoWork(mytask g)
{

Response.Write("hello");
//here the custom function is executed//
g();

}

before this will work you need to add events or functions to the delegate, before it is passed into the DoWork function.

example

mytask thetask=new mytask(); //make a new instance of the delegate
thetask+=new mytask(someobject.somemethod); //assign the event to the delegate
ClassA temp=new ClassA(); //make a new classA
temp.DoWork(thetask); //tell classA to DoWork and 'thetask' will get executed in there
Response.Write("done");

NOW! once the DoWork is called for the temp object, inside the DoWork method, someobject.somemethod is executed ( before the response.write("done") ).

In conclusion the delegate object is like a cast for a function to be executed, you are passing an event into a function to be executed.

NB, in this example my delegate was a void, if the function you want to pass in returns a value you have to match it to a string delegate or double delegate etc etc.

For a more detailed explanation see

http://www.superdotnet.com/Article.aspx?ArticleID=192

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home