0

Like many other posts I've found on SO, I'm trying to get my head around delegates. Hopefully this example is not classed a duplicate because I am asking a specific question about a particular example.

 public delegate void HelloFunctionDelegate(string message);

    public class Delegate
    {
        static void Main()
        {
            HelloFunctionDelegate del = new HelloFunctionDelegate(GoodNight); // delegate will point to the GoodNight method

            del("Hello"); // invoke the delegate
        }

        public static void GoodMorning(string strMessage)
        {
            Console.WriteLine(strMessage + " and good morning!");
            Console.ReadKey();
        }

        public static void GoodNight(string strMessage)
        {
            Console.WriteLine(strMessage + " and good night!");
            Console.ReadKey();
        }
    }

So in my example I understand that my delegate is a reference to any function that matches its signature and if I pass in GoodMorning I will see: Hello and good morning!

and if I pass in GoodNight I will see: Hello and good night!

So its kind of like going through a middle man...

I don't understand is what's the point, why wouldn't I just directly call my GoodMorning / GoodNight methods as and when I need to use them?

Maybe there are better examples for when a delegate is useful, but in this example, why don't I just bypass the middle man?

Cœur
  • 37,241
  • 25
  • 195
  • 267
JsonStatham
  • 9,770
  • 27
  • 100
  • 181
  • You can have delayed execution. Or take the `.ForEach()` extension method for example, it takes a delegate that will be executed for item in a list. Therefore these delegates are delayed in their execution. – Callum Linington Feb 26 '16 at 11:48
  • Try searching, plenty of duplicates exist. – CodeCaster Feb 26 '16 at 11:48
  • Read my question and you will notice I already mention the fact that I've read many other posts, I want a reason for this particular example. – JsonStatham Feb 26 '16 at 11:50
  • 2
    You wouldn't use delegates in this example, you use them when you don't know what the required behaviour is and have it provided to you as a parameter. – Lee Feb 26 '16 at 11:51
  • I've already looked at the answer you have rather crudely slapped on the top of this question too and I didn't find it helpful. – JsonStatham Feb 26 '16 at 11:52
  • This guy always explains things really well: https://www.youtube.com/watch?v=rxLNJ8jCN1c&index=3&list=PLAE7FECFFFCBE1A54 – Dennis_E Feb 26 '16 at 11:54
  • 1
    You just happened to find [a zero-voted answer](http://stackoverflow.com/a/30253989/), posted in 2015 to a 2009 question, while all the other answers in [that question](http://stackoverflow.com/questions/1735203/delegates-in-c-sharp), all of which have at least one upvote, _do_ a good job at explaining when and why to use delegates. So the answer to your question _"Why do they use delegates like this"_ is _"Because they're trying to show an example, but don't quite do a good job at that"_. If we were to post a question about every, well, less-than-perfect answer, we'd have an infinite loop. – CodeCaster Feb 26 '16 at 11:55
  • VTC as opinion based. If you want to know what the writer of [the answer you are quoting](http://stackoverflow.com/a/30253989) was thinking, you should ask them. – AakashM Feb 26 '16 at 12:16

2 Answers2

3

Since you are asking concretely about this example and not in general: There is no point to doing that in this particular piece of code. It teaches you the mechanics of delegates but it does not teach you the point of using them.

In short, the point is that some piece of code can take a reference to a method without knowing what method it will actually receive. It can later call that delegate at will. That enables more abstractions than otherwise possible.

usr
  • 168,620
  • 35
  • 240
  • 369
0

Consider you have the following delegate:

public delegate void CarEvent(Car car);

And then you have an implementation like the following:

public class Car : DataRecord
{
    // An event to execute when the record is deleted
    public CarEvent OnDelete { get; set; }

    public void Delete()
    {
        this.DeleteRecord(); // Deletes this record from ex. the database

        if (OnDelete)
        {
            OnDelete(this); // Executes the event
        }
    }
}

By using a delegate you can subscribe different methods to the OnDelete allowing you to do different things when the record is deleted.

Ex. you can make it so when the record is deleted it's deleted from a "ListView" that holds it.

public class CarList : ListView
{
    public CarList()
        : base()
    {
        foreach (var car in CarRecords.LoadCars())
        {
            var listViewItem = new ListViewItem(car);
            car.OnDelete = this.DeleteCarFromList;

            this.Items.Add(listViewItem);
        }
    }

    private void DeleteCarFromList(Car deletedCar)
    {
        this.Items.Remove(deletedCar);
    }
}

Of course the above is a rough example and there is a lot more things and different kind of situations where you can use delegates and most notably if you want to use them for events you should consider implementing them using the event keyword. - https://msdn.microsoft.com/en-us/library/awbftdfh.aspx

All in all you want to use delegates when the behavior may differ depending on the overall implementation of something. Like you might want to do one thing in one situation and something else in another situation, but they should both over-all do the same thing.

If you do not need different behaviors based on implementation then there's no need to use delegates. You'd always want to call a method directly if possible.

I hope this explained it okay.

Bauss
  • 2,767
  • 24
  • 28