Delegates in .NET

hand-010 I received the following question:

What is a delegate?  What problem does it solve?  and When might I use a delegate?

A delegate is essentially a function pointer.  We have used function pointers in various scenarios in the past to solve the problem of needing to execute user-defined code inside of another function or to fire events using the observed/observable programming pattern.

The problem we’ve always had with function pointers in the past is that there has never been any type safety.  If I had a variable that was supposed to point to a function, I could assign it any function.  So if the function the code is expecting returns a string and takes an integer and a string as parameters, I could assign the variable a function that returned nothing (void) and passed nothing.  My code would compile, but when I got to that function, the chances are my code would blow up on me.

Of course this would be a problem in any language that doesn’t implement type safety.  But in languages that do implement type safety, not implementing type safety at the function pointer level is especially dangerous.  Since the compiler is catching all of these kinds of errors for us everywhere else, we naturally expect it will catch this error for us too.

Very simply, delegates are type-safe function pointers.

To declare a delegate, we first need to declare a delegate type:

delegate void Foo(string s,int a);

and then to declare a variable of type Foo:

Foo myFooPointer;

we can now use myFooPointer as though it were a function:

myFooPointer("abc", 23);


Of course, if you use a variable without assigning something to it, you would throw an exception.  It is no different with variables that are delegates.  What we need is a function that takes a string and an integer as parameters that we can assign to myFooPointer:

public void Foo2(string s, int a)
{
}

myFooPointer = Foo2;

You may never have to use delegates directly, but they are used under the hood of .NET primarily for assigning event handlers to variables so that when an event is triggered, .NET knows what function to call.

Delegates also show up in a lot of the threading APIs.  So, if you plan on doing a lot of multi-threaded programming, you’ll be a lot more likely to encounter delegates there.

Other places talking about Delegates:

Delegates in VB.NET – developerFusion – the global developer community – In your Visual Basic.NET journey, you have definitely encountered a well used but little understood phenomenon called a delegate. You use them everyday, but might not know it. In this article, we will take a look at what a delegate is …

.NET Delegates: A C# Bedtime Story – developerFusion – the global … – NET world. In this talk, David De Florinier and Gojko Adzic show how Monorail makes it easy to develop .NET based AJAX applications, and how to use the Castle Project to build Web 2.0 applications effectively. …

.NET Delegates Part 1 – Delegates are one concept in code that gets at all 3 of the above characteristics. A delegate is not all that easy to explain, but I’ll do my best, given my experience with them, and the value I find in them, at a practical level. …

Understanding .NET Delegates – I’ve read several articles and chapters in books that introduce the concept of delegates. I always understood the concept, but could never quite figure out the implementation. Well, today I ran into a scenario where I knew I could …

C# .Net Delegates : Arrays of Delegates « Shiman’s Weblog – Creating an array of delegates is the same as creating an array of any type. Selecting from a set of tasks at run time is an example of when an array of delegates is essential to an elegant solution. The switch statement is one solution …

 

Other post in Advanced CSharp

Related Post

  • Silverlight – Wire up your form for programmingSilverlight – Wire up your form for programming As I mentioned a couple of weeks ago, learning Silverlight is a lot more about relearning some basic assumptions than it is about learning a new language.  We've already looked at the […]
  • Response.Redirect() executes too soon on the Server.Response.Redirect() executes too soon on the Server. I've seen this question a couple of times in various situations. The first involves Javascript and the second involves server side code. Both are caused by a misunderstanding of what […]
  • jQuery – EventsjQuery – Events As well as being able to change the class associated with an element or a set of elements on a screen, jQuery also allows you to fire events.  You might want to do this, for example, if […]
  • Making values nullableMaking values nullable First, a little history lesson. When .NET was first released, we had value types and object types.  The difference between the two is that you do not have to set aside memory for a […]
  • Stackalloc in CSharpStackalloc in CSharp In the last few weeks we've looked at several keywords from the CSharp language that allow us to deal with memory management directly.  Stackalloc is another keyword from that […]

About Dave Bush

Dave Bush is a .NET programmer and Certified ScrumMaster who is passionate about managing risk as it relates to developing software. When he is not writing or speaking about topics related to Application Lifecycle Risk Management (ALRM), he is an example to his peers as he develops web sites in the ASP.NET environment using industry best practices.

One Pingback/Trackback

  • http://jeffmartin.com Jeff Martin

    I think your explanation is a bit out of order, you want to declare the delegate, then assign it to Foo2, then use it.

    if you did it in the order you are describing – i think you would throw a null reference exception.

    (Granted its not all the same section of code, but someone new may not understand).

  • Dave

    It is true that it would throw an exception just like using any other variable that had not been assigned would throw one.

    The trick in explaining something is always in what order does it make the most sense.

  • Pingback: Self Executing Anonymous Function

Awards & Certs