Friday, December 25, 2015

Generic Delegates in C#

In today's post, we will be discussing generic delegates in C#.

Generic Delegates

Previously, I talked about basics of delegates here. In that example, we used the Employee class for our delegate. The arguments of Employee type were hard-coded and the delegate could not be used with any other data type.

Generic Delegates in C#

With generic delegates we can make the delegate to use a generic type and be flexible with the actual type being used in the delegate.
Let's try to understand this with an example:

Suppose, we have a Person class:

public class Person
    public int Id { get; set; }

And an Employee class like this:

public class Employee : Person
    //Employee properties

So for comparing any class objects, let's have a generic delegate type:

public delegate bool AreEqual<T>(T a, T b);

For the actual instance, we can have any class like this:

bool AreSamePerson<T>(T a, T b) where T: Person

As we discussed constraints last week here, by having constraints we will be able to use the specific properties of Person class in our method definition.

So let's put them all together to see how it works:

public delegate bool AreEqual<T>(T a, T b);

static void Main(string[] args)
      var employeeA = new Employee() {Id = 1};
      var employeeB = new Employee() {Id = 2};
      var employeeC = new Employee() {Id = 1};

      AreEqual<Employee> IsEmployeeSame = 
        new AreEqual<Employee&gt(AreSamePerson<Employee>);

      Console.WriteLine(IsEmployeeSame(employeeA, employeeB));  
      Console.WriteLine(IsEmployeeSame(employeeA, employeeC));  


static bool AreSamePerson<T>(T a, T b) where T: Person
     return (a.Id == b.Id);

So here we created three employees and compared them. We saw how the generic delegate can take any method (with appropriate signature) and can be used in our code. For delegate instances, we can have different methods (maybe with different constraints) which can be used with the delegate. This way we can generalize our generics and use them.

I can have separate method for IsEmployeeSame and IsPersonSame. If I want to add a new type, for example, Manager deriving from Person and I want it to use AreSamePerson to compare, I can do that or if I want to write a new AreManagerEqual (with Manager type) method, I can also do that.


So in this post, we saw how generic delegates can be useful to us along with an example. The flexibility it provides can help us in different situations.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)

No comments:

Post a Comment