Tell me more ×
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

4 Answers

for C++ devs : delegates are like function pointers, but as objects with type check

for Java devs: delegates are interfaces with only one method

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

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

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
1  
+1 for a terrific pun! – Morgan Herlocker May 11 '11 at 12:59
It is not the pun. Usually you fully understand things only after having explained them to others – Геннадий-Ванин Feb 17 at 3:41

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 – Геннадий-Ванин Feb 17 at 4:43
@GennadyVanin--Novosibirsk: msdn.microsoft.com/en-us/library/ms173171(v=vs.80).aspx – back2dos Feb 17 at 15:45

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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