Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

February 24, 2016

Understanding C# Delegates

Filed under: C#,LINQ @ 12:10 pm
Tags:

Delegates are sometimes seen as an ethereal concept, bodiless and hard to grasp. But they don’t have to be that way.

In my latest Pluralsight course: “C# Best Practices: Collections and Generics“, I walk through what a delegate is and how to understand them.

image

A delegate is simply a type that represents a reference to a method with a specific parameter list and return type. The primary purpose of delegates is to pass methods as arguments to other methods.

Here is an example of a method that needs a delegate:

var filteredList = vendors.Where(???);

In the above line of code, we use the LINQ Where method to filter a list of vendors. The Where method needs a selector defining the logic to be used for the filtering. Do we want to filter the list of vendors by some keyword in their name? Or by how much they currently owe us? Or by the product types that they sell? Somehow we need to specify this logic. We do that with a method.

What does that method need to look like? In Visual Studio, Intellisense shows us the signature of the delegate method that it needs. For the LINQ Where method, it is:

vendors.Where(Func<Vendor, bool> predicate)

Let’s break down what Intellisense is telling us here:

  • The “Func” specifies that the method we create has to return a value. If the method does not require a return value, the Intellisense will instead say “Action”.
  • The first generic parameter (Vendor in this example) is the first parameter to the method we create.
  • If there is a return value, the last generic parameter (bool in this example) defines the return value type.

So looking at the example, we know we need to create a method with a bool return value that takes one parameter of type Vendor.

We can then create a method such as this:

private bool FilterCompanies(Vendor v)
{
   return v.CompanyName.Contains(“Toy”);
}

This method takes in a Vendor object and returns a Boolean. Specifically, it returns true if the vendor’s company name contains “Toy”. Otherwise it returns false, thereby specifying how we want the vendor list filtered.

We can then pass this method as a delegate to the Where method:

var filteredList = vendors.Where(FilterCompanies);

The resulting filteredList contains the list of vendors whose company name contains “Toy”.

The problem with this approach is that we end up with little methods all over that simply define these delegates. There is another way. We can use Lambda Expressions. Lambda Expressions are basically a short cut syntax for these little methods.

So instead of this:

var filteredList = vendors.Where(FilterCompanies);

private bool FilterCompanies(Vendor v)
{
   return v.CompanyName.Contains(“Toy”);
}

We can simply type this:

var filteredList = vendors.Where(v => v.CompanyName.Contains(“Toy”));

For more information, check out: “C# Best Practices: Collections and Generics” from Pluralsight.

Enjoy!

6 Comments

  1.   Ygor lazaro — February 25, 2016 @ 5:58 am    Reply

    Nice explanations, but there’s a missing ) at the last sample.

    🙂

    •   deborahk — February 25, 2016 @ 1:37 pm    Reply

      Great catch! Thanks for letting me know! I just fixed it above. Thanks again!

  2.   infocyde — March 1, 2016 @ 1:45 pm    Reply

    Thanks. I come back and learn delegates and then forget about them all the time. I’m sure I use the backed in ones all the time but making my own doesn’t come up maybe as much as it should. Saved your explanation locally for later when I need it, thanks.

  3.   Junaid Ahmed — April 6, 2016 @ 1:58 am    Reply

    Hi Deborahk,
    Thanks for publishing such excellent tutorials. I am taking your course C sharp Best Practice, and Generic and Collection. I think every student should learn from your tutorial to become a good programmer.

    •   deborahk — April 14, 2016 @ 9:22 am    Reply

      Thank you so much for the kind words about my Pluralsight course: C# Best Practices: Collections and Generics!

  4.   Francisco Pineda — January 17, 2017 @ 2:29 am    Reply

    Hi Deborah, when can I find the code for the Practical Linq Course at plural sight that include the database ACM

    Thank you,

    FRANCISCO JAVIER

Trackbacks/Pingbacks

  1. Dew Drop – February 25, 2016 (#2196) | Morning Dew

RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2023 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs