Jimmy Lillegaard
Jimmy Lillegaard

Reputation: 129

Understanding Delegates and Delegate Syntax

I have this line of code, it works but I don't understand it:

Genres.Find(delegate (Genre genre) { return genre.Id == id; });

Genres is a list of genre(music)

What exactly is happening here?

Upvotes: 0

Views: 117

Answers (4)

Waescher
Waescher

Reputation: 5737

It says, find the Genre (from the list Genres) which has the Id equal to the value from the variable id.

The keyword delegate says, that this is a kind of inline function which decides whether the check is true for each item or not. The beginning (Genre genre) says "given I would call each element genre in the loop, I can check each items' Id with its named variable Id". This is: genre.Id == id.

A modern approach would be the usage of lambdas like:

var x = Genres.Find(g => g.Id == id);

In this case g is your loop variable you can check against.

Upvotes: 1

The One
The One

Reputation: 4784

An intuitive way to see it:

Genres.Find(   --- The CompareGenres function is being called from here ---    );

 bool CompareGenres(Genre genre)
 {
   return genre.Id == id; 
 }

Find accepts a Predicate < T >, T is the type of the parameter, in this case: you're passing an instance of Genre which is being supplied by the Find method.

"The Predicate is a delegate to a method that returns true if the object passed to it matches the conditions defined in the delegate."

So you're just passing a method as a parameter in the form of a delegate

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

C# provides two ways of defining delegates without writing a named method for it - the old anonymous method syntax introduced in C# 2.0, and the shorter lambda syntax introduced in C# 3.0.

Your code is the old way of writing this:

Genres.Find(genre => genre.Id == id);

This article describes the evolution of anonymous functions in C#.

Your Find method takes a predicate delegate. Depending on the version of .NET targeted by your code it may or may not be the System.Predicate<T> delegate, but its functionality is equivalent. An anonymous method in parentheses provides an implementation of your predicate, allowing you to pass arbitrary conditions to your Find(...) method.

Upvotes: 3

Matthias
Matthias

Reputation: 1436

Maybe I do not use the right terms here. But form an abstract point of view: The Find method here accepts a delegate as parameter. It allows you to implement the "find" algorithm (here comparing the id). It is flexible code you could also compare any other object of "genre".

Upvotes: 0

Related Questions