Delegates in .NET
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
- Two Interfaces. Same Method. Two meanings. - September 29th, 2008
- Making values nullable - October 9th, 2008
- CSharp's Property Shortcuts - October 23rd, 2008
- Readonly variables in CSharp? Really?! - October 29th, 2008
- Dispose with Using - November 10th, 2008
- Delegates in .NET - December 4th, 2008
- Using Sealed in CSharp - December 8th, 2008
- CSharp checked and unchecked - December 11th, 2008
- Advanced CSharp - unsafe mode - December 15th, 2008
- Volatile variables and CSharp threads - December 22nd, 2008
- What is the global keyword in CSharp? - December 29th, 2008
- CSharp fixed keyword - January 5th, 2009
- using - There's more there than you are using - February 2nd, 2009
- Stackalloc in CSharp - February 16th, 2009
- Removing Warnings from CSharp Compile Cycle - March 10th, 2009
- && vs & and | vs ||... What's the difference? - March 16th, 2009
- Advanced CSharp - yield - March 25th, 2009
- Just say “No!” to C# Regions? Really?! - April 16th, 2009
- C# “” better than string.Empty? - April 20th, 2009
- .Net String Pool – Not Just For The Compiler - April 22nd, 2009
- CSharp ?? Operator - May 18th, 2009
- Using VB.NET From CSharp - July 1st, 2009
- Dispose, Finalize and SuppressFinalize - July 9th, 2009
- What is .NET’s Object.GetHashCode() Used For? - August 5th, 2009
- ASP.NET Substitution Control - October 22nd, 2009
Other Related Items:
Express Digital Darkroom Professional Edition Workflow Software, Full Version for the Professional Specializing in Portrait, Wedding, Sports or Event Photography, for Windows.For Professional Photographers: Sports, Event, Portrait, and Wedding Photographers. Created for Professional Photographers, this software manages the... Read More >
Kelsyus Backpack ChairMake time to relax in the Kelsyus® backpack chair, featuring armrests that easily convert to backpack shoulder straps so transport is never an issue.
Head First C#Head First C# is a complete learning experience for object-oriented programming, C#, and the Visual Studio IDE. Built for your brain, this book cov... Read More >










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).
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.