Click here to Skip to main content
15,908,264 members
Please Sign up or sign in to vote.
2.33/5 (3 votes)
See more:
I am beginner in programming. I am not able to understand why we create delegate. Please help me with your valuable answers. I have tried one small program by using delegate and then try to write same logic without using delegate. If without delegate also we can do our task, then what is the use of delegate. Please consider following coding with and without delegate.

What I have tried:

With Delegate:

C#
using System;
using System.Collections.Generic;

class Pragim
{
    public static void Main()
    {
        List<employee> empList = new List<employee>();
        empList.Add(new Employee() { ID = 1, Name = "A", Salary = 10000, Experience = 3 });
        empList.Add(new Employee() { ID = 1, Name = "B", Salary = 11000, Experience = 7 });
        empList.Add(new Employee() { ID = 1, Name = "C", Salary = 12000, Experience = 3 });
        empList.Add(new Employee() { ID = 1, Name = "D", Salary = 13000, Experience = 5 });
        empList.Add(new Employee() { ID = 1, Name = "E", Salary = 14000, Experience = 4 });

        IsPromotable isPromotable = new IsPromotable(Promote);
        Employee.PromoteEmployee(empList, isPromotable);
        Console.ReadLine();
    }
    public static bool Promote(Employee emp)
    {
        if (emp.Experience >= 5)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

delegate bool IsPromotable(Employee empl);

class Employee
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int Salary { get; set; }
    public int Experience { get; set; }

    public static void PromoteEmployee(List<employee> employeeList, IsPromotable IsEligibleToPromote)
    {
        foreach (Employee employee in employeeList)
        {
            if (IsEligibleToPromote(employee))
            {
                Console.WriteLine(employee.Name + " has been promoted");
            }
        }
    }
}




Without Delegate:

C#
using System;
using System.Collections.Generic;

class Pragim
{
    public static void Main()
    {
        List<employee> empList = new List<employee>();
        empList.Add(new Employee() { ID = 1, Name = "A", Salary = 10000, Experience = 3 });
        empList.Add(new Employee() { ID = 1, Name = "B", Salary = 11000, Experience = 7 });
        empList.Add(new Employee() { ID = 1, Name = "C", Salary = 12000, Experience = 3 });
        empList.Add(new Employee() { ID = 1, Name = "D", Salary = 13000, Experience = 5 });
        empList.Add(new Employee() { ID = 1, Name = "E", Salary = 14000, Experience = 4 });

        
        Employee.PromoteEmployee(empList);
        Console.ReadLine();
    }
    public static bool Promote(Employee emp)
    {
        if (emp.Experience >= 5)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

class Employee
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int Salary { get; set; }
    public int Experience { get; set; }

    public static void PromoteEmployee(List<employee> employeeList)
    {
        foreach (Employee employee in employeeList)
        {
            if (Pragim.Promote(employee))
            {
                Console.WriteLine(employee.Name + " has been promoted");
            }
        }
    }
}
Posted
Updated 1-Oct-19 10:25am
v2

Delegates are pointers to functions which lets you pass different methods to PromoteEmployee. So you are doing

IsPromotable isPromotable = new IsPromotable(Promote);
Employee.PromoteEmployee(empList, isPromotable);


however you could do something like

IsPromotable isPromotable = IsManager ? new IsPromotable(PromoteManager) : new IsPromotable(Promote);
Employee.PromoteEmployee(empList, isPromotable);


So you can pass a reference to different functions depending on your requirements, and that method is then called inside PromoteEmployee.

If you don't have a requirement to do this, however, then don't, use the non-delegate version of your code. delegates are normally used for events where the method to call has to be passed to the item that triggers the event.
 
Share this answer
 
Delegates are complicated fellows, and you can do a lot with them - but in many cases developers don;t even realise they are involved at all ...
Events are all delegate based; a delegate is a collection of function pointers which provide the mechanism for you to add handlers:
C#
DynamicArgument da = DynamicArgument.Create();
            da.ArgumentReceived += Application_ArgumentReceived;

private void Application_ArgumentReceived(object sender, DynamicArgument.DynamicArgmentEventArgs e)
    {
    tbData.Text += "\r\n" + e.Argument;
    }
ArgumentReceived is a delegate, which adds your handler to the event chain so that when the DynamicArgument class raises the event, all the methods that has "subscribed" to the delegate will get executed in turn. But you don't really see that until you start creating your own Events for a class - and even then in modern code, the delegate itself is "hidden" behind a layor of abstraction:
C#
/// <summary>
/// Event to indicate program argument available
/// </summary>
public event EventHandler<DynamicArgmentEventArgs> ArgumentReceived;
/// <summary>
/// Called to signal to subscribers that program argument available
/// </summary>
/// <param name="e"></param>
protected virtual void OnArgumentReceived(DynamicArgmentEventArgs e)
    {
    ArgumentReceived?.Invoke(this, e);
    }

But that's not the only thing you can do with them: you can use an array of delegates to select a function to execute: which is pretty much what a switch block does: it =uses an index into an array of delegates to run a specific piece of code instead of having to do if ... else if ... else if ... else.
You can use them to pass a specific print method into a generic system: perhaps you want the same code to generate different results for a supervisor and a peon? Use a delegate as a parameter and you can pass the right method and the remaining code is unchanged.

Loads of things you can do with them - most of which you will meet when you get a little further in your course!
 
Share this answer
 
Comments
BillWoodruff 1-Oct-19 17:20pm    
I've posted a 'high-altitude' view I hope is complementary to yours: there's something 'slippery' about .NET delegates that a lot of people have trouble mastering. I think part of the difficulty is distinguishing a 'pure' function pointer from a structure that maintains a queue of subscriber-code pointers.
OriginalGriff 1-Oct-19 17:34pm    
And it deserved a +5
BillWoodruff 1-Oct-19 18:11pm    
And you, also !
Modern GUI programming is driven by events ... these events can happen at any time; they are asynchronous.

We attach (bind) event-handlers to objects (Controls, Classes, OS facilities like the file system): these handlers are references (function pointers) to executable code (call-backs) packaged in a special .NET structure called a Delegate.

We write the Delegate as a kind of template, a specification of its parameters and return type. Then we bind (attach) an instance of the Delegate to an appropriate trigger event, like a button click, or a change in a watched folder/file.

As OriginalGriff shows you in his example, you can define your own Events; there is a special Delegate structure of the form: void delegate(object sender, EventArgs e) that is the default EventHandler for many types of .NET Control events.

A feature of Delegates is that multiple subscribers/clients can bind to the same Delegate, and all get called in FIFO order when the Delegate is invoked/executed: hence, the term "multicast" delegate. Subscribers are added using the special '+= operator.

The internal list of subscriber-code (queue) is not directly accessible; to remove a subscriber-code you must keep a reference to it, and then use '-= to remove it. To remove all subscribers gets tricky, and is an advanced topic.

There are many other uses for Delegates, and C# 3.0 added the 'Action, 'Func, and 'Predicate Types that allow using them with less code complexity.
 
Share this answer
 
Comments
CHill60 2-Oct-19 5:05am    
Clearest explanation I think I've ever seen - +5!
BillWoodruff 2-Oct-19 5:58am    
thank you !

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900