Delegate Interview Questions and Answers in C#

Delegate Interview Questions and Answers in C#

In this article, I am going to discuss most frequently asked Delegate Interview Questions and Answers in C#. Please read our previous article where we discussed the most frequently asked String Interview Questions in C# with Answers. As part of this article, we are going to discuss the following Delegates Interview Questions and Answers in C#.

  1. What is a Delegate in C#? Explain with one example.
  2. Types of Delegates in C#.
  3. What is Single Cast Delegate in C#
  4. What is Multicast Delegate in C#? Explain with one example.
  5. Where do you use multicast delegates?
  6. Where did you use delegates in your project?
What is a Delegate in C#? Explain with one example.

We can call a method that is defined in a class in two ways

Using Object: We can call the method using the object of the class if it is a non-static method or we can call the method through class name if it is a static method.

Using Class Name: We can call a method by using a delegate also. Calling a method using delegate will be faster in execution compared to the first process.

A delegate is also a user-defined type and before invoking a method using delegate we must have to define that delegate first. A delegate is a type-safe function pointer that means a delegate holds the reference of a method and then calls the method for execution.

The signature of the delegate must match the signature of the function, the delegate points to otherwise we will get a compiler error. This is the reason delegates are called as type-safe function pointers.

A Delegate is similar to a class. We can create an instance of it and when we do so, we pass the function name as a parameter to the delegate constructor, and it is the function name that the delegate points to.

Types of Delegates in C#:

Delegates are classified into two types such as

  1. Single cast delegate
  2. Multicast delegate

If a delegate is used for invoking a single method then it is called a single cast delegate or unicast delegate. OR the delegates that represent only a single function is known as a single cast delegate.

If a delegate is used for invoking multiple methods then it is known as the multicast delegate. OR the delegates that represent more than one function are called Multicast delegate.

Note: If we want to call multiple methods using a single delegate the I/O parameters of all those methods must be the same.

Tip to remember delegate syntax: 

Delegates syntax look very much similar to a method with a delegate keyword.

Sample Delegate Program:
Delegate Interview Questions and Answers in C#
What is Multicast Delegate in C#? Explain with one example.

A Multicast delegate is a delegate that has references to more than one function. When we invoke a multicast delegate, all the functions are invoked that the delegate is pointing to. There are 2 approaches to create a multicast delegate.

Approach1: 

namespace Sample
{
    public delegate void SampleDelegate();
    public class Sample
    {
        static void Main()
        {
            SampleDelegate del1 = new SampleDelegate(SampleMethodOne);
            SampleDelegate del2 = new SampleDelegate(SampleMethodTwo);
            SampleDelegate del3 = new SampleDelegate(SampleMethodThree);
            // In this example del4 is a multicast delegate. We use +(plus) 
            // operator to chain delegates together and -(minus) operator to remove.
            SampleDelegate del4 = del1 + del2 + del3 - del2;

            del4();
        }

        public static void SampleMethodOne()
        {
            Console.WriteLine("SampleMethodOne Invoked");
        }
        public static void SampleMethodTwo()
        {
            Console.WriteLine("SampleMethodTwo Invoked");
        }
        public static void SampleMethodThree()
        {
            Console.WriteLine("SampleMethodThree Invoked");
        }
    }
}

Approach2:

namespace Sample
{
    public delegate void SampleDelegate();
    public class Sample
    {
        static void Main()
        {
            // In this example del is a multicast delegate. You use += operator 
            // to chain delegates together and -= operator to remove.
            SampleDelegate del = new SampleDelegate(SampleMethodOne);
            del += SampleMethodTwo;
            del += SampleMethodThree;
            del -= SampleMethodTwo;
            del();
        }

        public static void SampleMethodOne()
        {
            Console.WriteLine("SampleMethodOne Invoked");
        }
        public static void SampleMethodTwo()
        {
            Console.WriteLine("SampleMethodTwo Invoked");
        }

        public static void SampleMethodThree()
        {
            Console.WriteLine("SampleMethodThree Invoked");
        }
    }
}

Note: A multicast delegate invokes the methods in the invocation list, in the same order in which they are added.

If the delegate has a return type other than void and if the delegate is a multicast delegate, only the value of the last invoked method will be returned. Along the same lines, if the delegate has an out parameter, the value of the output parameter will be the value assigned by the last method.

Where do you use multicast delegates?

Multicast delegate makes the implementation of observer design pattern very simple. The observer pattern is also called a publish/subscribe pattern.

Where did you use delegates in your project? Or how did you use delegates in your project?

The Delegate is one of the very important aspects to understand. Most of the interviewers ask you to explain the usage of delegates in a real-time project that you have worked on. 

Delegates are extensively used by framework developers. Let us say we have a class called Employee as shown below.

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

The Employee class has the following properties.

  1. Id
  2. Name
  3. Experience
  4. Salary

Now I want to write a method in the Employee class which can be used to promote employees. The method should take a list of Employee objects as a parameter and should print the names of all the employees who are eligible for a promotion. But the logic based on which the employee gets promoted should not be hardcoded. At times we may promote employees based on their experience and at times we may promote them based on their salary or maybe some other condition. So, the logic to promote employees should not be hard-coded within the method.

How to achieve?

To achieve this we can make use of delegates. So now I would design my class as shown below. We also created a delegate EligibleToPromote. This delegate takes the Employee object as a parameter and returns a boolean. In the Employee class, we have the PromoteEmpoloyee method. This method takes a list of Employees and a Delegate of type EligibleToPromote as parameters. The method then loops through each employee object and passes it to the delegate. If the delegate returns true, then them Employee is promoted, else not promoted. So within the method, we have not hard coded any logic on how we want to promote employees.

namespace DelegateDemo
{
    public delegate bool EligibleToPromotion(Employee EmployeeToPromotion);

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

        public static void PromoteEmployee(List<Employee> lstEmployees, EligibleToPromotion IsEmployeeEligible)
        {
            foreach (Employee employee in lstEmployees)
            {
                if (IsEmployeeEligible(employee))
                {
                    Console.WriteLine("Employee {0} Promoted", employee.Name);
                }
            }
        }
    }
}

So now the client who uses the Employee class has the flexibility of determining the logic on how they want to promote their employees as shown below. First create the employee objects – E1, E2, and E3. Populate the properties for the respective objects. We then create an employeeList to hold all the 3 employees.

Notice the private Promote method that we have created. This method has the logic of how we want to promote our employees. The method is then passed as a parameter to the delegate. Also, note this method has the same signature as that of EligibleToPromote delegate. This is very important because the Promote method cannot be passed as a parameter to the delegate if the signature differs. This is the reason why delegates are called as type-safe function pointers. 

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

        public static void PromoteEmployee(List<Employee> lstEmployees, EligibleToPromotion IsEmployeeEligible)
        {
            foreach (Employee employee in lstEmployees)
            {
                if (IsEmployeeEligible(employee))
                {
                    Console.WriteLine("Employee {0} Promoted", employee.Name);
                }
            }
        }
    }

    class Program
    {
        static void Main()
        {
            Employee emp1 = new Employee()
            {
                ID = 101,
                Name = "Pranaya",
                Experience = 5,
                Salary = 10000
            };

            Employee emp2 = new Employee()
            {
                ID = 102,
                Name = "Kumar",
                Experience = 10,
                Salary = 20000
            };

            Employee emp3 = new Employee()
            {
                ID = 103,
                Name = "Rout",
                Experience = 20,
                Salary = 30000
            };

            List<Employee> lstEmployess = new List<Employee>();
            lstEmployess.Add(emp1);
            lstEmployess.Add(emp2);
            lstEmployess.Add(emp3);

            EligibleToPromotion eligibleTopromote = new EligibleToPromotion(Program.Promote);
            Employee.PromoteEmployee(lstEmployess, eligibleTopromote);

            Console.ReadKey();
        }

        public static bool Promote(Employee employee)
        {
            if (employee.Salary > 10000)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}

So if we did not have the concept of delegates it would not have been possible to pass a function as a parameter. As the Promote method in the Employee class makes use of delegate, it is possible to dynamically decide the logic on how we want to promote employees.

Using Lambda expressions

In C Sharp 3.0 Lambda expressions are introduced. So you can make use of lambda expressions instead of creating a function and then an instance of a delegate and then passing the function as a parameter to the delegate. The sample example rewritten using Lambda expression is shown below. The private Promote method is no longer required now.

class Program
    {
        static void Main()
        {
            Employee emp1 = new Employee()
            {
                ID = 101,
                Name = "Pranaya",
                Experience = 5,
                Salary = 10000
            };

            Employee emp2 = new Employee()
            {
                ID = 102,
                Name = "Kumar",
                Experience = 10,
                Salary = 20000
            };

            Employee emp3 = new Employee()
            {
                ID = 103,
                Name = "Rout",
                Experience = 20,
                Salary = 30000
            };

            List<Employee> lstEmployess = new List<Employee>();
            lstEmployess.Add(emp1);
            lstEmployess.Add(emp2);
            lstEmployess.Add(emp3);

            Employee.PromoteEmployee(lstEmployess, x => x.Experience > 5);
        }
    }

In the next article, I am going to discuss the most frequently asked Nested Types Interview Questions and Answers in C#. Here, in this article, I try to explain most frequently asked Delegate Interview Questions and Answers in C#. I hope this article will help you with your needs. I would like to have your feedback. Please post your feedback, question, or comments about this article.

1 thought on “Delegate Interview Questions and Answers in C#”

Leave a Reply

Your email address will not be published. Required fields are marked *