Delegate Interview Questions C#.NET

Delegate Interview Questions and Answers C#.NET

In this article, I am going to discuss most frequently asked Delegate Interview Questions and Answers on C#.NET.

What is Delegate? Explain with one Example.

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

Using Object:

  1. We can call the method using 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:

  1. 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 of 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.

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 as 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 as 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 Declaration. 
public delegate void HelloFunctionDelegate(string Message);
class Pragim
{
    public static void Main()
    {
        // Create an instance of the delegate and pass the function name as the parameter 
        // to the constructor. The passed function signature must match the signature of the delegate
        HelloFunctionDelegate del = new HelloFunctionDelegate(Pragim.Hello);

        // Invoke the delegate, which will invoke the method
        del("Hello from Delegte");
        Console.ReadKey();
    }
    public static void Hello(string strMessge)
    {
        Console.WriteLine(strMessge);
    }
}
What is Multicast Delegate? 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.

Example: Multicast delegate with an int return type
namespace DelegateDemo
{
    // Deletegate's return type is int
    public delegate int SampleDelegate();
    public class Sample
    {
        static void Main()
        {
            SampleDelegate del = new SampleDelegate(SampleMethodOne);
            del += SampleMethodTwo;
            // The ValueReturnedByDelegate will be 2, returned by the SampleMethodTwo(),
            // as it is the last method in the invocation list.
            int ValueReturnedByDelegate = del();
            Console.WriteLine("Returned Value = {0}", ValueReturnedByDelegate);
        }
        // This method returns one
        public static int SampleMethodOne()
        {
            return 1;
        }
        // This method returns two
        public static int SampleMethodTwo()
        {
            return 2;
        }
    }
}
Example: Multicast delegate with an integer output parameter.
namespace DelegateDemo
{
    // Deletegate has an int output parameter
    public delegate void SampleDelegate(out int Integer);
    public class Sample
    {
        static void Main()
        {
            SampleDelegate del = new SampleDelegate(SampleMethodOne);
            del += SampleMethodTwo;

            // The ValueFromOutPutParameter will be 2, initialized by SampleMethodTwo(),
            // as it is the last method in the invocation list.
            int ValueFromOutPutParameter;
            del(out ValueFromOutPutParameter);
            Console.WriteLine("Returned Value = {0}", ValueFromOutPutParameter);
        }

        // This method sets ouput parameter Number to 1
        public static void SampleMethodOne(out int Number)
        {
            Number = 1;
        }

        // This method sets the ouput parameter Number to 2
        public static void SampleMethodTwo(out int Number)
        {
            Number = 2;
        }
    }
}
Where do you use multicast delegates?

Multicast delegate makes implementation of observer design pattern very simple. Observer pattern is also called as 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 Employee object as a parameter and returns a boolean. In the Employee class, we have PromoteEmpoloyee method. This method takes a list of Employees and a Delegate of type EligibleToPromote as parameters. The method then loops thru 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 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. 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);
        }
    }

If you want to learn Delegates in Detail with examples, then please follow the below articles

Delegates in C#

Multicast Delegates in C#

Delegates Realtime example in C#

Anonymous Method in C#

Lambda Expressions in C#

Generic Delegates in C#

SUMMARY

In this article, I try to explain most frequently asked Delegate Interview Questions and Answers on C#.NET. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

1 thought on “Delegate Interview Questions C#.NET”

Leave a Reply

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