Brent Waggoner, Web Developer


C# Delegates for Dummies: What Can a Delegate Do?

Confession time: I’ve been developing in .NET for over 7 years, and have given very little thought to delegates. I would say it’s possible to be a better than average developer and never have to directly deal with delegates outside of certain Webforms components. So this series is for me as well as anyone reading.

That doesn’t mean, however, that delegates aren’t important. We use them every day, in many ways, behind the scenes, and, not only can knowing how to use them simplify our code on a day to day basis, but a deeper understanding of delegates will help us really grok the .NET framework as a whole on a deeper level.

I’ll spend some time later on in this series talking about exactly what delegates are, but for now, this is the essential piece of information:

Delegates are types for functions.

Clear as mud, I know, but let’s look at a simple example which should clarify what I mean. Take a look at the code below:

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

    public int Subtract(int x, int y)
    {
      return x - y;
    }

    public int Multiply(int x, int y)
    {
      return x * y;
    }

    public int Divide(int x, int y)
    {
      return x / y;
    }
  }


var calc = new Calculator();

Console.Write(calc.Add(1, 1));        //2
Console.Write(calc.Subtract(5, 1));   //4
Console.Write(calc.Multiply(2, 3));   //6
Console.Write(calc.Divide(4, 2));     //2

This code is fine for what it is, and doesn’t really need to be made any more complex. It does make a decent test case for delegates though, since it’s simple enough that it should be clear what’s happening. The Calculator class is being instantiated, then used to call whatever operation needs to occur. Let’s say we wanted to be able to keep our operations in a separate class, so they could be used in other places without being replicated. Delegates can help us out here. Let’s start by building another class to hold our operators, and removing the operators from our Calculator class, while refactoring it to use a delegate.

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

    public static int Subtract(int x, int y)
    {
      return x - y;
    }

    public static int Multiply(int x, int y)
    {
      return x * y;
    }

    public static int Divide(int x, int y)
    {
      return x / y;
    }
  }

  public delegate int Operation(int x, int y);

  public class Calculator {
    public Operation FunctionOperator { get; set; }

    public Calculator(Operation operatorDelegate) {
        FunctionOperator = operatorDelegate;
    }

    public int Calculate(int x, int y) {
        return FunctionOperator(x, y);
    }
  }

Now we can call the function as follows:

var calc = new Calculator(Operations.Add);
var result = calc.Calculate(1, 2); //result will equal 3

calc.FunctionOperator = Operations.Multiply;
var result = calc.Calculate(3, 6); //result will equal 18

Now, rather than calling a different operation on our calc object,  we can simply instantiate it and pass in the predefined function from our Operations class. We can also change the current function being passed in through the delegate.

In our simple example, this may not be necessary, but in the context of a larger application, where we may add new operations on a regular basis that need to be accessible at different points throughout our system, we can save ourselves a lot of code duplication.

It’s unlikely that you’d ever set up an application exactly like this, as .NET provides a lot of other options for working with delegates, but knowing how they work in their simplest form gives a deeper understanding of what’s going on behind the scenes. We’ll talk about more fun delegate tricks in upcoming blog posts.

I Build Things

Need a solution for your website or business? Contact Me!


Recent Posts

What I Do

I love to build things. I love making the web work.

Tools I Use:

  • C#
  • .NET MVC
  • Javascript / jQuery
  • Angular
  • PHP
  • SQL / MySQL

But what really matters is solving your problems. I can do that too.

What I've Done

  • JointCharge joint supplement is a great product that needed a great site. With a responsive layout and a custom eCommerce solution, they're helping more pets than ever.

  • IlluminedNation helps match the right person to the right job. We automated their process so companies could more easily benefit from their experise.

  • Diamond Deluxe is one of three sites that needed a responsive makeover without a whole new design. Using Bootstrap and some custom menus, we moved it into the mobile age.

What Can I Do For You?

Need a web site? Fill out the form below and I'll contact you to work out the details. Or email me directly at brent.waggoner@gmail.com

Thanks for your request!