Click here to Skip to main content
15,867,488 members
Articles / Programming Languages / C# 4.0
Tip/Trick

Simple Delegates in a Nutshell

Rate me:
Please Sign up or sign in to vote.
4.60/5 (3 votes)
21 May 2013CPOL2 min read 14.3K   9   3
The easiest, most straight-forward delegate tutorial.

Introduction

When first learning C#, I had a hard time understanding how to use delegates. Once I grasped the idea and realized how easy they are to use, I made a place for them everywhere in my code. In this tutorial I’ll show you the basics behind properly implementing delegates. First, if you don’t know… 

A delegate is a type that references a method. Once a delegate is assigned a method, it behaves exactly like that method. The delegate method can be used like any other method, with parameters and a return value…~ MSDN

A delegate is someone designated to represent someone else. When coding, a delegate represents a method

A great example for using delegates is a simple calculator.

Calculator Scenario  

Say you want to perform an operation on two numbers, x and y. That operation can be addition, subtraction, multiplication or division. The parameters are the same no matter which type of calculation you want to perform.

C#
double z = x + y;
double z = x - y;
double z = x * y;
double z = x / y;

The only difference in the above code is the operator that’s used. That being the case what if we could call one method and pass in a parameter telling us which operator to use? That’s where delegates come into play.

Delegates represent Methods 

Let's define a delegate and the methods that it will represent:

C#
private delegate double CalculateDelegate(double x, double y);
private          double Add              (double x, double y) { return x + y; }
private          double Subtract         (double x, double y) { return x - y; }
private          double Multiply         (double x, double y) { return x * y; }
private          double Divide           (double x, double y) { return x / y; }

As you can see, the method definitions and the delegate method look the same except for the "delegate" keyword in front of the return type. Think of the delegate method as a template of the type of method in which it can call. For instance, a delegate method with a return type of string can only represent a method with the return type of string

Also notice that the delegate method looks like a normal method except that it has no method body. That's because it's going to call the body of the method that it's referencing. But how does a delegate know which method to call? 

Calling All Methods!

You have to decide which method the delegate will call by assigning that method to the delegate. Let's say I want to call the Add() method. Let's instantiate a delegate variable:

C#
private CalculateDelegate calculate = new CalculateDelegate(Add);

The delegate variable calculate now represents the Add() method. So now when you call:

C#
double result = calculate(3, 5);

the variable result will equal 8.

Put It Together

Here is a quick sample:

C#
class Program {
    static void Main(string[] args) {
        Calculator calc = new Calculator();
        double result = calc.Calculate(Calculator.CalculateTypeEnum.Multiply, 5, 3);
        Console.WriteLine(result);
        Console.Read();
    }
    public class Calculator {
        internal double Calculate(CalculateTypeEnum type,double x, double y) {
            switch (type) {
                case CalculateTypeEnum.Add:
                    calculate = new CalculateDelegate(Add);
                    break;
                case CalculateTypeEnum.Subtract:
                    calculate = new CalculateDelegate(Subtract);
                    break;
                case CalculateTypeEnum.Multiply:
                    calculate = new CalculateDelegate(Multiply);
                    break;
                case CalculateTypeEnum.Divide:
                    calculate = new CalculateDelegate(Divide);
                    break;
            }
            return calculate(x, y);
        }

        private double Add(double x, double y) { return x + y; }
        private double Subtract(double x, double y) { return x - y; }
        private double Multiply(double x, double y) { return x * y; }
        private double Divide(double x, double y) { return x / y; }

        public enum CalculateTypeEnum {
            Add,
            Subtract,
            Multiply,
            Divide
        }

        private delegate double CalculateDelegate(double x, double y);
        private CalculateDelegate calculate;
    }
}

And This is Just the Beginning! 

Delegates are very powerful. Especially when you start using Callbacks and Anonymous Methods. If anyone finds this helpful then I'll do a Callbacks in a Nutshell tutorial. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
PraiseExcellent and simple explanation Pin
Member 131448577-Jun-18 22:03
Member 131448577-Jun-18 22:03 
GeneralMy vote of 5 Pin
not_starman22-May-13 12:07
not_starman22-May-13 12:07 
GeneralRe: My vote of 5 Pin
jay1_z29-May-13 4:21
jay1_z29-May-13 4:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.