Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I was reviewing Andrew Troelsen book on C# 4.0. The part that explains delegates starts as smooth as:

public class SimpleMath
{
    //declare delegate
    public delegate int BinaryOp(int x, int y);

    public static int Add(int x, int y)
    {
    return x + y;
    }
}

class Program
{
    static void Main(string[] args)
    {
    //create delegate which points to Add method
    BinaryOp b = new BinaryOp(SimpleMath.Add);

    //Invoke Add method using delegate
    Console.WriteLine("10 + 10 is {0}", b(10,10));
    Console.ReadLine();
    }
}

than gets as complicated as

public class Car
{
    public int CurrentSpeed {get;set;}
    public int MaxSpeed {get;set;}
    private bool carIsDead {get;set;}
    public Car() {MaxSpeed=10;}
    public Car(int maxSpeed, int currentSpeed)
    {
        MaxSpeed = maxSpeed;
        CurrentSpeed = currentSpeed;
    }
    //declare delegate
    public delegate void CarEngineHandler(string msgForCaller);
    //define member of this delegate
    private CarEngineHandler listOfHandlers;
    //add registration function for the caller
    public void RegisterWithCarEngine(CarEngineHandler methodToCall)
    {
        listOfHandlers = methodToCall;
    }

    public void Accelerate(int delta)
    {
            if (carIsDead)
            {
                    if (listOfHandlers!=null)
                            listOfHandlers("Sorry, the car is dead");
            }
            else {
                    CurrentSpeed+=delta;
                    if (10== (MaxSpeed - CurrentSpeed) && listOfHandlers!=null)
                    {
                            listOfHandlers("Gonna blow!");
                    }
                    if (CurrentSpeed >= MaxSpeed)
                            carIsDead = true;
                    else
                            Console.WriteLine("Current Speed = {0}", CurrentSpeed);
            }
    }
}

If we try to pick that content and teach somebody else, we are going to find a hard time, since it becomes tricky.

How would you teach C# delegates in a way he/she is able to understand clearly when to use them?

share|improve this question

closed as unclear what you're asking by Ozz, MichaelT, gnat, psr, Bart van Ingen Schenau Jul 26 '13 at 12:58

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question.If this question can be reworded to fit the rules in the help center, please edit the question.

8  
I'd tell the newbie to go ask someone else. There you go! You just taught him how delegate works. –  Mathew Foscarini Jul 25 '13 at 13:03
add comment

5 Answers 5

A common strategy for teaching any technique is, at first describe some problem which is quite hard to solve or insolvable without the technique. Then introduce the technique solving the problem in a elegant easier way. It can be applied to delegates also.

A very common use of delegate is to map a function with other variables. You can use a dictionary with integer or string keys and delegates to show the functionality. But before that give the problem to the learners to solve in their way. If you can show that your implementation is easier, you are done.

And if anyone came from C/C++ and knows about function pointers, you can just tell them 'delegate' is the C# version of function-pointers.

share|improve this answer
    
+1 for "describe some problem which is quite hard to solve or insolvable without the technique. Then introduce the technique solving the problem in a elegant easier way." –  StuperUser May 11 '11 at 11:41
    
+1... yes, describe a problem where the solution involves delegates. Even when I thought I understood what delegates were it still didn't make any sense why they were used until I came across a problem that delegates helped solved. –  Dal May 12 '11 at 7:29
add comment

for C++ devs : delegates are like function pointers, but are type safe

for Java devs: delegates are interfaces with only one method

for C# devs/newbies: Say you come up with a new brilliant algorithm to trade MS shares. For given prices you can estimate future price. You want to compare how it performs comparing to the old one. Your testing function (pseudocode)

res1 = test_algo(prices, from, to, new_algo)
res2 = test_algo(prices, from, to, old_algo)
if (res1 > res2) 
    // yeah baby!

new_algo and old_algo are delegates.

share|improve this answer
    
+1 for "interfaces with only one method". That's exactly how it first clicked with me as a Java programmer. –  Travis Christian May 11 '11 at 15:08
2  
And what if C# is the person's first programming language? –  l46kok Jul 26 '13 at 1:56
    
@l46kok before learning delegates is good to know what are interfaces :) same as Java applies. Good enough mental model for beginners –  lukas Jul 26 '13 at 9:08
2  
I don't see the relationship between interfaces and delegates being particularly useful. Coming from a JavaScript background, it was best described to me as "delegates are functions placed into variables" (which is sorta second-nature in JS). –  Graham Jul 26 '13 at 13:52
add comment

Delegate to him to teach you and then fill in the blanks.

this is far better as it motivates him to pick up an ability of "self learning" which is essential for programming.

share|improve this answer
3  
+1 for a terrific pun! –  Morgan Herlocker May 11 '11 at 12:59
2  
It is not the pun. Usually you fully understand things only after having explained them to others –  Gennady Vanin Novosibirsk Feb 17 '13 at 3:41
add comment

I think the name delegate and the whole terminology around it is a little strange.

Basically, delegates are first class functions, i.e. functions, that are values in every sense. A simple language like JavaScript should help illustrating what this means within a short time.
That knowledge can then be translated to C# delegates and lambdas.

share|improve this answer
    
Delegates are NOT functions, they are classes. One cannot declare/define a method/function outside of a class (in a namespace) in C#. The delegate can be declared/defined outside of a class definition –  Gennady Vanin Novosibirsk Feb 17 '13 at 4:43
    
@GennadyVanin--Novosibirsk: msdn.microsoft.com/en-us/library/ms173171(v=vs.80).aspx –  back2dos Feb 17 '13 at 15:45
1  
I never settled too much into them, but it sounds like Delegates are the declaration of a function-type (return type, arguments, etc.) Action<> and Func<> are the logical removal of this unnecessary cruft by letting you use generics syntax. It basically feelsl ike assigning a function to a variable. Once I understood those second ones, I never really bothered to learn what made delegates so great... –  Katana314 Jul 25 '13 at 14:42
add comment

It really depends on how skilled the developer already is. Assuming that C# is the first language that the developer has ever learned and that this is the first time that they have heard of delegates, I would begin by talking through things that the student already knows. They already know, by this time how to use methods.

void Method(int parameter, double otherParameter)
{
    //Do something useful
}

// elsewhere in code
Method(12, 124.675);

They should already understand this concept. And this works very well when you have the data and only need to do one thing to it in all cases.

But what if you don't know what needs to be done with the data? What if you have a list of widgets from different manufacturers which all have their own implementations of Method(int parameter, double otherParameter)? What then?

At this point, the student will probably come up with a solution like the following:

foreach(var widget in widgetList)
{
    widget.Method(12, 124.675);
}

This will be a good answer to that question. So the next question that you should ask is this: "What happens when each widget has a different name for Method?"

Particularly smart students might suggest using an adapter pattern to handle this case. Which is great, let them create their adapter and generate all of that code. Other, less switched on students may get stumped at this point. For the ones who suggest the adapter pattern, tell them that there are a hundred different types of widget, all of which have a different name for Method. What would they do then?

This is the point to introduce them to the idea of delegates. "What if I told you that instead of creating adapters, we could delegate responsibility for deciding what to call to the widget instead of the calling code?" Here is where you explain delegates and how they can be used to hold a reference to a function.

To draw a parallel, explain to them how it is the same concept as holding a reference to a class, except instead of a group of functions with some related data, a delegate holds a reference to only one function. And that function has a specific signature, just like how an int can only hold a specific type of data.

share|improve this answer
1  
+1 Very nice answer, especially that last paragraph –  paul Jul 26 '13 at 12:09
    
Thank you! I appreciate it. –  Stephen Jul 29 '13 at 7:43
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.