var blog = new ThoughtStream(me); RSS 2.0
 Thursday, October 09, 2008

A coworker just asked me this question - what's the point of delegates in .NET? My answer was very short and one that he had not found online: to delay execution of a method.

Consider this: if you pass a Method2 as a parameter to Method1, Method2 is evaluated immediately and the result is passed into Method1.

public class SomeObject
{
    public void Method1(int someValue)
    {
        //... code here
    }
}
 
...
 
someObject.Method1(anotherObject.Method2());

Additionally, Method2 must have a return value (not void) so that the value returned from Method2 can be passed as the parameter of Method1.

With a delegate, though, we get method pointers that can be used to delay the execution of the method in question until it's needed (if at all). We can also get rid of the requirement for a return value and we can pass values that were created by the host method, into the delegate method.

public class SomeObject
{
    public void Method1(Action<int> someAction)
    {
        //.. do some stuff here
        int aValue = GetTheValueFromSomeWhere();
        someAction(aValue);
        //... do some more here
    }
}
 
public class AnotherObject
{
    public void Method2(int aValue)
    {
        //do something that is dependent on aValue, here.
        int i = aValue + 1; // or anything else that needs aValue.
    }
}

FYI - Action (void return; with many parameterized variations) is a delegate that is build into .NET 3.5, along with Func<T> (return value of type T; with many parameterized variations). These are the two most common delegates that I use in my code.

Most .NET developers have used delegates without realizing it, too. The event system in .NET is nothing more than a multi-cast delegate - a delegate that points to more than one method - with a special signature and syntax (depending on the language being used).

There's a lot of good use for delegates. And like any other tools, there's a lot of bad uses. Take the time to learn what they are, how they work, and where they can be beneficial.

Thursday, October 09, 2008 4:05:00 PM (Central Standard Time, UTC-06:00)  #    Comments [0]. Trackback 
Tags: .NET

Comments are closed.
Navigation
About Me
View Derick Bailey's profile on LinkedIn

Send mail to the author(s) Contact Me
Archive
<July 2010>
SunMonTueWedThuFriSat
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Derick Bailey
Sign In
Statistics
Total Posts: 115
This Year: 0
This Month: 0
This Week: 0
Comments: 44
Themes
Pick a theme:
All Content © 2010, Derick Bailey
DasBlog theme 'Business' created by Christoph De Baene (delarou)