Ziff-Davis Enterprise 
DevSource: Microsoft Developer Resource
Add OnsArchitectureLanguagesTechniquesUsing VSForums
 
Home arrow Languages arrow A Quick Description of C# Delegates
A Quick Description of C# Delegates
By Jeff Cogswell

Rate This Article:
Add This Article To:
A Quick Description of C# Delegates
( Page 1 of 2 )

In this short article, Jeff Cogswell provides a very quick explanation of what exactly delegates are in C#.

Perhaps one of the most common questions among people learning C# is this: What is a delegate? In this article, I describe what a delegate is and show you several examples so you can get up to speed on it as soon as possible.

Essentially, a delegate is an object that contains a reference to a method. This method can be either a static method for a class or a member method for a particular instance.

ADVERTISEMENT

This might sound vague, so let's look at a specific example. Or, if you're in a hurry or already understand things like pointers in other languages, you can skip to the last section of this article called The Quick Answer.

First example: Form events

Here's an example of where you would encounter such a thing. Suppose you have a form with a button on it. Inside the form's class, you have a method that handle's the button's click. That is, this method runs when you click the button.

Behind the scenes, how does the .NET code know to call your handler method? The form stores a reference to this method. The type of variable used for this storage is a delegate.

Click here for the article Working with Delegates in C#, which is a longer, more thorough explanation of C# delegates.

Now suppose you create a second instance of this same form class, and when your program runs, you display both instances. You now have two forms on the screen that are the same, and you have two instances of your form class. When you click the button on the second form, the method for the second instance runs. How does the .NET code know to run the handler for the particular instance? The answer is the delegate can store a reference to a method for a particular class instance.

Let's be more specific. Create a new C# windows application with a single form. Put a TextBox control and a Button control on the form. Add a handler for your button's OnClick event, which displays a message box showing the text in the TextBox control.

Here's the code that does this, assuming the TextBox control is called TextBox1 and the button is called Button1. (I removed the unneeded using statements).

using System;
using System.Windows.Forms;

namespace DelegateApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, 
        EventArgs e)
        {
            MessageBox.Show(textBox1.Text);
        }
    }
}

When you run this, type something into the TextBox control, and click the button, you'll see a message box open showing you what you typed. Then close the program and return to Visual Studio.

Now let's add code to open two windows. From Solution Explorer, open the Program.cs file. Add the following two lines shown in blue bold.

static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Form1 x = new Form1();
    x.Show();
    Application.Run(new Form1());
}

This code will open another copy of your form. Save the file and run your program. Now you'll see two forms that look the same. In one form type abc into the text box. In the second form, type def. Return to the first (abc) form, and click the button. What you see should be no surprise; the message box shows abc. Close the message box, and go to the second form. Click the button. Again, no surprise: The message box shows def. Now close the message box and the two forms.

Internally, each instance of the form class holds a variable that's a delegate pointing to the method for the respective instance. When the event fires and your event handler code runs, the code runs for its respective instance. In other words, the delegate holds not only a reference to your event handler method, but also a reference to the particular instance for the method. (Technically, there's only one copy of the code; internally, the runtime lets your method know which instance the method is associated with.)

That's all a delegate is: A variable that holds a method of a class, and, optionally, an instance. Or, more formally, a delegate is an object that contains a reference to a method and optionally a reference to an instance.

Second example: Class methods

A delegate doesn't have to be associated with a particular instance. In the previous example, you saw that the delegate stored a method that went with a particular instance of the form class. You can also store a method that goes with an entire class, that is, a static method.

In the following section, The Quick Answer, I show you code that demonstrates both types.



 
 
>>> More Languages Articles          >>> More By Jeff Cogswell
 



DevSource video
Devsource Video Series
Manipulating Society through Technology
Jeremy Bailenson, Director of the Virtual Human Interaction Lab at Stanford University, talks about virtual reality, avatars, Moore's law, how real world behaviors influence online reality, and societal manipulation through technology!
>> Play video
>> Read article
>> See all videos
DevLife Blog

Julia explores the Robotics Studio! (It's for more than you think.)

MSDev Blog

Messages for Bill Gates!

Make it Work
.NET makes runtime type checking a breeze. See what Peter has to say about it in this week's tips!
News
Microsoft Counts on App Support for Vista
Microsoft has taken pains to demonstrate that Windows Vista will have ample application support.
DevSource RSS FEEDS
XML Want an easy way to keep up with breaking tech news? And the Get DevSource headlines delivered to your desktop with RSS.