Can you explain me code below :
private static List<Post> _Posts;
public static Post GetPost(Guid id)
{
return _Posts.Find(delegate(Post p)
{
return p.Id == id;
});
}
What is the point to find an object in a generic list by that way ? He can simply iterate the list.
How this delegated method called for each element of list ?
NOTE : if this has a common name, can you update my question's title ?
Thanks !
As mentioned, delegates are reference types and are used to reference any method that has the same signature. In contrast to them, the anonymous functions are all about passing code block or code as a delegate parameter. Sometimes they are referred to as "anonymous delegates" too.
Limitations of Anonymous MethodsAny unsafe codes cannot be accessed inside anonymous methods. There cannot be jump statements such as goto, break or continue inside anonymous methods. Anonymous methods cannot be used on the left side of the is operator.
Anonymous methods are basically functions without a name, with the ability to create closures. Lambda expressions are constructs that are convertible to both anonymous methods and expression trees, and follow more complex rules of type inference than anonymous methods.
Anonymous Method is an inline code that can be used wherever a delegate type is expected. Microsoft introduced Anonymous Methods in C# 2.0 somewhere around 2003. Lambda expression is an anonymous method that you can use to create delegates or expression tree types.
You're quite right he can iterate over the list, you can think of the code in your question as being conceptually the same as the following:
private static Post GetPost(Guid id)
{
Post p = default(Post);
foreach (Post post in _Posts)
{
if (post.Id == id)
{
p = post;
break;
}
}
return p;
}
It requires less code to write your snippet and importantly you are now saying what you want to be found and not exactly how to find it:
private static Post GetPost(Guid id)
{
return _Posts.Find(delegate(Post p)
{
return p.Id == id;
});
}
In C# 3.0 this can be shortened further using what is called a "lambda expression" to:
private static Post NewGetPost(Guid id)
{
return _Posts.Find(p => p.Id == id);
}
Using the least amount of readable code to achieve the same goal makes both writers and readers of that code happier.
He is using an anonymous delegate. He could have used a lambda expression instead:
Posts.Find(p => p.Id == id)
Also, wrapping access to the list in a method achieves nothing in this case and exposes the elements of the list to external callers. This is bad practice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With