Delegate

The delegate in C#. Like someone said: “Never understood delegates for the last 5 years except that it is function pointer.” That could be me.

That concept is not that difficult: a delegate is a variable in the code, but instead of a value it is used to refer to a method.

The syntax of the declaration must match the method it must refer to.

public string GetName(int id)
{ ... }

When you want to use this method in a delegate:

public delegate string GetNameDelegate(int id)

Before I didn’t get a grip on the concept, now it’s a bit more clear, but why should I use a delegate? Let the internet speak:

In programming, you are often faced with situations where you need to execute a particular action, but you don’t know in advance which method, or even which object, you’ll want to call upon to execute it. For example, you might want to tell an object to play a media file during runtime, but you might not know what object will be playing the file, or whether it’s a video, a sound file, an animation, or something else. Rather than hardcoding a particular media player object, you would create a delegate, and then resolve that delegate to a particular method when the program executes.

source

Currently I’m more into using Depency Injection (IoC) and the factory Design Pattern to accomplish this. It’s all about Separation of Concerns.

I write my code with interfaces. One class does not known the other class, only the properties and methods in the interface. However, sometimes I want to do a callback, but my class does not known anything about the class who is using the it. In that case I use an event, and that is in fact a delegate.

More about the delegate

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s