2

I found this piece of code in an answer on stackoverflow. htmlWeb.PreRequest does not seem to be an event handler because += tab tab is not generating required code and its symbol in IntelliSense tells me that it is a normal member variable.

Please explain this syntax. Is this an event handler or is it something else? I have seen += is usually used for adding event handlers. I searched on Google for terms like "ways to add event handler in c#" but couldn't find any such code.

Please help me understand this code. I understand the meaning of this code but not the syntax. Any other example would be appreciated.

HtmlWeb htmlWeb = new HtmlWeb();
htmlWeb.PreRequest += request =>
{
    request.CookieContainer = new System.Net.CookieContainer();
    return true;
};
3
  • 2
    very good article about lambda expressions codeproject.com/Articles/507985/Way-to-Lambda Jun 21, 2013 at 5:21
  • Updated title - feel free to change/revert ... it is not possible to find a name something that you don't know name for :) Jun 21, 2013 at 5:28
  • exactly, I had not not known what to put in title. Now it is easy to search. Thnx @AlexeiLevenkov
    – shashwat
    Jun 21, 2013 at 5:32

3 Answers 3

5

Your code:

HtmlWeb htmlWeb = new HtmlWeb();
htmlWeb.PreRequest += request =>
{
    request.CookieContainer = new System.Net.CookieContainer();
    return true;
};

actually is quivalent to:

bool PreRequest_EventHandler(HttpWebRequest request)
{
    request.CookieContainer = new System.Net.CookieContainer();
    return true;
}
//...
HtmlWeb htmlWeb = new HtmlWeb();
htmlWeb.PreRequest += PreRequest_EventHandler;

The key difference is that it uses lambda expressions syntax instead of declaring a separate method. As it's said in the linked MSDN artcile lambda syntax has the following form:

(input parameters) => expression

So request => in your code is the input parameter. The brackets are omitted as there is only one parameter. If there were two or more, it would be (x,y)=>....

6
  • Thanks @horgh for that good explanation. I still have one question that += tab tab won't work here than how am I supposed to get the signature of the Event Handler..? Only reading documentations..?
    – shashwat
    Jun 21, 2013 at 6:18
  • @harsh sorry, I couldn't catch what you mean. What is tab? You may press tab button for the Visual Studio to automatically generate a separate method with the correct signature. Or you may hover mouse over the left side of the assignment (the event itself), VS should give a hint...Is this what you need?
    – horgh
    Jun 21, 2013 at 6:21
  • no key sequence += Tab Tab not generating any code. No hint in Tooltip of VS intellisense
    – shashwat
    Jun 21, 2013 at 6:28
  • 1. you may use F12 button to procees to the declaration and see the type and the signature of the delegate. 2. you may += new , then IntelliSense would suggest the correct type...use it and add a bracket 3. Just google it
    – horgh
    Jun 21, 2013 at 6:30
  • Tab button didn't work, as htmlWeb.PreRequest is a delegate, not an event.
    – horgh
    Jun 21, 2013 at 6:33
2

PreRequest is not a method, but rather a delegate:

http://htmlagilitypack.codeplex.com/SourceControl/latest#Trunk/HtmlAgilityPack/HtmlWeb.cs

So the lambda you've shown simply is assigning an anonymous method to said delegate that is used internally by HtmlAgilityPack to determine if some extra work is needed to correctly process the current request object, as shown here:

if (PreRequest != null)
{
    // allow our user to change the request at will
    if (!PreRequest(req))
    {
        return HttpStatusCode.ResetContent;
    }
}

When the condition if(!PreRequest(req))... is evaluated, it uses the anonymous method, which adds some extra "stuff" to the current request object, and then returns true (which ! then negates), so HAP knows to not return quite yet.

In case it's not all that clear, you don't supply the request object. HAP does that in the Get() method in which this delegate is being used:

req = WebRequest.Create(uri) as HttpWebRequest;

Your delegate is basically just supplying a method body to potentially do something to that request and then return either true or false.

0

This is an example of an Anonymous Methods (C# Programming Guide)

In versions of C# previous to 2.0, the only way to declare a delegate was to use named methods. C# 2.0 introduces anonymous methods.

Creating anonymous methods is essentially a way to pass a code block as a delegate parameter.

By using anonymous methods, you reduce the coding overhead in instantiating delegates by eliminating the need to create a separate method.

So, basically, this is using an Anonymous method as the event handler.

2
  • I still can't find the way is parameter being passed. What is this called..? += request => ..? There is no parenthesis where parameters are supposed to kept inside. I have seen this in LINQ but never like this.
    – shashwat
    Jun 21, 2013 at 5:23
  • The argument is request. The parenthesis are optional if there's only one argument, but it could be put like += (request) => ... Jun 21, 2013 at 6:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.