What’s The Point Of Delegates In .NET?

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.


Post Footer automatically generated by Add Post Footer Plugin for wordpress.

About Derick Bailey

Derick Bailey is an entrepreneur, problem solver (and creator? :P ), software developer, screecaster, writer, blogger, speaker and technology leader in central Texas (north of Austin). He runs SignalLeaf.com - the amazingly awesome podcast audio hosting service that everyone should be using, and WatchMeCode.net where he throws down the JavaScript gauntlets to get you up to speed. He has been a professional software developer since the late 90's, and has been writing code since the late 80's. Find me on twitter: @derickbailey, @mutedsolutions, @backbonejsclass Find me on the web: SignalLeaf, WatchMeCode, Kendo UI blog, MarionetteJS, My Github profile, On Google+.
This entry was posted in Uncategorized. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • http://realfiction.net Frank Quednau

    Indeed, that characteristic of delegates came useful to an idea we are developing, which is basically a set of classes providing configuration APIs for setting up hierarchies of Windows Forms Controls. You don’t really want to create the Control hierarchy when you are using the config API, instead delegates are set up in the proper way, and once the user calls the Setup(Control c) method all Action delegates created during the configuration can be executed. This also provides the advantage that youc an reuse such a Control Setup instance.

  • Maxim

    Never thought about the “delaying execution”. Hummm thanks :)

  • http://rant.blackapache.net/ OJ

    I think that your summation is PART of the answer, but not an answer as a whole. Delegates are used in scenarios where you are not delaying the execution of code, such as varying functionality based on state.

  • http://www.lostechies.com/blogs/derickbailey derick.bailey

    @OJ

    The very nature of delegates will always be a delayed execution of the code they point to, no matter the intended use of the delegate.

    public void Foo(Action bar)
    {
    bar();
    }

    or

    Action bar = new Action(someMethod);
    bar();

    these are the most basic examples of using a delegate, and both of them are illustrations of delayed code execution – whether it’s one wait cycle that is imperceptable by a human is irrelevant. The runtime is delaying the execution of the delegate’s target until the delegate is invoked.