<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:copyright="http://blogs.law.harvard.edu/tech/rss" xmlns:image="http://purl.org/rss/1.0/modules/image/">
    <channel>
        <title>General .NET</title>
        <link>http://geekswithblogs.net/dotnetnomad/category/7212.aspx</link>
        <description>General musings or information posts regarding the .NET Framework.</description>
        <language>en-US</language>
        <copyright>newman</copyright>
        <managingEditor>newman.de@gmail.com</managingEditor>
        <generator>Subtext Version 0.0.0.0</generator>
        <item>
            <title>.NET WinPCap Update (Filtering, Windows Extensions)</title>
            <link>http://geekswithblogs.net/dotnetnomad/archive/2008/02/13/119535.aspx</link>
            <description>&lt;p&gt;Wow. Turns out this thing might be useful to more than just me.  Anyway, I've added P/Invoke calls to allow access to the WinPCap functions that are specific to Windows as well as the packet filtering functions.  I've added a port of the packet filtering example as well.  I can't say I've tested all the calls yet, regardless, at this point I am going to start moving up to a higher level.  I think we should now have access to almost all the calls available in the native WinPCap, but feel free to leave a comment to let me know otherwise.&lt;/p&gt;  &lt;p&gt;   &lt;/p&gt;&lt;div class="wlWriterSmartContent" id="scid:18d43e01-4549-4fde-8ca6-c7b4b7385fac:bfd1fcab-40e9-49e3-8b32-be47b9a96d87" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;p&gt;Download Solution - &lt;a href="http://geekswithblogs.net/images/geekswithblogs_net/dotnetnomad/WindowsLiveWriter/ee0.NETWinPCapUpdateFilteringWindowsExte_93C2/Nomad.Net.PacketCapture_2.zip"&gt;Nomad.Net.PacketCapture.zip&lt;/a&gt;&lt;/p&gt;&lt;/div&gt;   &lt;div class="wlWriterSmartContent" id="scid:18d43e01-4549-4fde-8ca6-c7b4b7385fac:031c152d-5bd7-48a3-8af5-a1548e247380" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;p&gt;Download Solution - &lt;a href="http://geekswithblogs.net/images/geekswithblogs_net/dotnetnomad/WindowsLiveWriter/ee0.NETWinPCapUpdateFilteringWindowsExte_93C2/Nomad.Net.PacketCapture.Examples_2.zip"&gt;Nomad.Net.PacketCapture.Examples.zip&lt;/a&gt;&lt;/p&gt;&lt;/div&gt; &lt;img src="http://geekswithblogs.net/dotnetnomad/aggbug/119535.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>newman</dc:creator>
            <guid>http://geekswithblogs.net/dotnetnomad/archive/2008/02/13/119535.aspx</guid>
            <pubDate>Wed, 13 Feb 2008 22:30:20 GMT</pubDate>
            <wfw:comment>http://geekswithblogs.net/dotnetnomad/comments/119535.aspx</wfw:comment>
            <comments>http://geekswithblogs.net/dotnetnomad/archive/2008/02/13/119535.aspx#feedback</comments>
            <slash:comments>5</slash:comments>
            <wfw:commentRss>http://geekswithblogs.net/dotnetnomad/comments/commentRss/119535.aspx</wfw:commentRss>
            <trackback:ping>http://geekswithblogs.net/dotnetnomad/services/trackbacks/119535.aspx</trackback:ping>
        </item>
        <item>
            <title>.NET WinPCap</title>
            <link>http://geekswithblogs.net/dotnetnomad/archive/2008/01/31/119140.aspx</link>
            <description>&lt;p&gt;As I stated in my last post, I am currently geeking out on packet capture software.  The &lt;a href="http://www.wireshark.org/" target="_blank"&gt;WireShark&lt;/a&gt; network analysis tool is pretty awesome and is built using the &lt;a href="http://www.winpcap.org/" target="_blank"&gt;WinPCap&lt;/a&gt; library which is itself a port of libpcap to the Win32 environment.  The unfortunate part, or at least for us .NET developers, is that there is no (IMHO of course) good .NET binding to WinPCap.  Well, I've gone ahead and spent some time getting an initial wrapper done using P/Invoke.&lt;/p&gt;  &lt;p&gt;I've taken a different initial strategy from &lt;a href="http://www.codeproject.com/KB/IP/dotnetwinpcap.aspx" target="_blank"&gt;the other&lt;/a&gt; project I found and I think it makes more sense in the long run.  The other project attempts to provide a more elegant binding by wrapping the native functions of WinPCap in a couple of simple objects.  This isn't necessarily bad, however the author decided to hide the actual P/Invoke calls, which means if you (like me) don't like his class structure, you can't simply use the P/Invokes directly to build your own.  So, I went ahead and I wrote my own set of P/Invoke calls to bind to WinPCap.&lt;/p&gt;  &lt;p&gt;I tried to stick to the following rules:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;All P/Invoke method name exactly match the native function names &lt;/li&gt;    &lt;li&gt;All managed type names used in marshalling exactly match the native struct names &lt;/li&gt;    &lt;li&gt;All method parameters in the P/Invokes have the same name as in their native functions &lt;/li&gt;    &lt;li&gt;Marshal parameters as closely as possible (i.e. don't just use IntPtr for everything) &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Of course, I couldn't stick to the rules 100% due to some technical limitations, but in most cases it is obvious where I deviated.&lt;/p&gt;  &lt;p&gt;We should see the following advantages from this:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;All documentation already in existence for WinPCap is still 100% relevant. &lt;/li&gt;    &lt;li&gt;All C/C++ code samples using the native WinPCap can be ported (more or less) directly into C# code. &lt;/li&gt;    &lt;li&gt;Developers now have the freedom to build their own tools using WinPCap in .NET using whatever class structure they'd like &lt;/li&gt; &lt;/ol&gt;  &lt;h3&gt;The Library&lt;/h3&gt;  &lt;p&gt;Aside from the supporting structs that are used to marshal the unmanaged types, there are only two classes you need to be concerned with in the library.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;WinPCapConstants&lt;/strong&gt; - Holds the constants translated from the #defines of the pcap.h header file&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;WinPCapDriver&lt;/strong&gt; - Static class that holds all P/Invoke declarations used to bind to WinPCap.  All functions except those that are listed in the WinPCap docs as Windows specific or dealing with packet filtering are currently available.  The Windows specific functions and packet filtering functions will be added as the project progresses.&lt;/p&gt;  &lt;p&gt; &lt;/p&gt;  &lt;p&gt;There is also one handy extension method that I added to help with marshalling the various data structures used by WinPCap.  It is defined as follows:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;namespace&lt;/span&gt; Nomad.Net.PacketCapture.Interop
{
    &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;static&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;class&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;IntPtrExtensions
&lt;/span&gt;    {

        &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;static&lt;/span&gt; TStruct AsStruct&amp;lt;TStruct&amp;gt;(&lt;span style="color: rgb(0,0,255)"&gt;this&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;IntPtr&lt;/span&gt; ptr)
        {

            &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; (TStruct)&lt;span style="color: rgb(43,145,175)"&gt;Marshal&lt;/span&gt;.PtrToStructure(ptr, &lt;span style="color: rgb(0,0,255)"&gt;typeof&lt;/span&gt;(TStruct));

        }

    }
}&lt;/pre&gt;

&lt;p&gt;Normally, we'd have to write something like the following to marshal a pcap_if structure from unmanaged to managed code:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: rgb(43,145,175)"&gt;pcap_if&lt;/span&gt; nic = (&lt;span style="color: rgb(43,145,175)"&gt;pcap_if&lt;/span&gt;)&lt;span style="color: rgb(43,145,175)"&gt;Marshal&lt;/span&gt;.PtrToStructure(nicPointer, &lt;span style="color: rgb(0,0,255)"&gt;typeof&lt;/span&gt;(&lt;span style="color: rgb(43,145,175)"&gt;pcap_if&lt;/span&gt;));&lt;/pre&gt;

&lt;p&gt;This is pretty heinous...In C we would have been able to just cast or dereference the pointer.  With the extension method above, the code becomes more readable:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: rgb(43,145,175)"&gt;pcap_if&lt;/span&gt; nic = nicPointer.AsStruct&amp;lt;&lt;span style="color: rgb(43,145,175)"&gt;pcap_if&lt;/span&gt;&amp;gt;();&lt;/pre&gt;

&lt;p&gt;It isn't all that much shorter in terms of length, but it reads much more like English.&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;h3&gt;&lt;/h3&gt;

&lt;h3&gt;Going Forward&lt;/h3&gt;

&lt;p&gt;My next step is to continue porting the original WinPCap examples from C to C#.  This will help me test the P/Invoke calls and learn more about WinPCap and how it is supposed to operate.  After that I will create my own higher-level wrapper using C# to abstract the details.  Again, the best part of all this is that if you don't like my high level code then you should still at least be able to access WinPCap via .NET, albeit in a more raw form.&lt;/p&gt;

&lt;p&gt;The following code should work, but you first need to install WinPCap.  I also recommend you download the developer pack so you can compare the native C examples with the couple of .NET ones I've done so far. The differences are relatively minor, but important since they mostly have to do with features/limitations of mixing C and .NET.  Also, the HTML based documentation for WinPCap is still valid, and I have yet to put much in the way of comments in my code.  &lt;/p&gt;

&lt;p&gt;Consider the following downloads as Alpha quality at best:&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;div class="wlWriterSmartContent" id="scid:18d43e01-4549-4fde-8ca6-c7b4b7385fac:fed35a5d-9839-4cd5-b857-7e5123a261ba" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;p&gt;Download Solution - &lt;a href="http://geekswithblogs.net/images/geekswithblogs_net/dotnetnomad/WindowsLiveWriter/8d1fd3964dd7.NETWinPCap_C572/Nomad.Net.PacketCapture_4.zip"&gt;Nomad.Net.PacketCapture.zip&lt;/a&gt;&lt;/p&gt;&lt;/div&gt;

&lt;p&gt;&lt;/p&gt;

&lt;div class="wlWriterSmartContent" id="scid:18d43e01-4549-4fde-8ca6-c7b4b7385fac:0ae5e96c-2b13-4b6b-8c98-58dff76b7d8d" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;p&gt;Download Solution - &lt;a href="http://geekswithblogs.net/images/geekswithblogs_net/dotnetnomad/WindowsLiveWriter/8d1fd3964dd7.NETWinPCap_C572/Nomad.Net.PacketCapture.Examples_4.zip"&gt;Nomad.Net.PacketCapture.Examples.zip&lt;/a&gt;&lt;/p&gt;&lt;/div&gt; &lt;img src="http://geekswithblogs.net/dotnetnomad/aggbug/119140.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>newman</dc:creator>
            <guid>http://geekswithblogs.net/dotnetnomad/archive/2008/01/31/119140.aspx</guid>
            <pubDate>Fri, 01 Feb 2008 02:26:15 GMT</pubDate>
            <wfw:comment>http://geekswithblogs.net/dotnetnomad/comments/119140.aspx</wfw:comment>
            <comments>http://geekswithblogs.net/dotnetnomad/archive/2008/01/31/119140.aspx#feedback</comments>
            <slash:comments>10</slash:comments>
            <wfw:commentRss>http://geekswithblogs.net/dotnetnomad/comments/commentRss/119140.aspx</wfw:commentRss>
            <trackback:ping>http://geekswithblogs.net/dotnetnomad/services/trackbacks/119140.aspx</trackback:ping>
        </item>
        <item>
            <title>WinPCap in Visual Studio 2008</title>
            <link>http://geekswithblogs.net/dotnetnomad/archive/2008/01/30/119088.aspx</link>
            <description>&lt;p&gt;In my copious amount of free time I've been messing around with network analysis and security.  I've always been generally interested in networking technology, but have never really had much practical exposure to it.  Sometimes, however, it is nice to be able to analyze a network and see what kind of information is actually coming across the wire.  In my last article I mentioned a tool called &lt;a href="http://www.wireshark.org/" target="_blank"&gt;WireShark&lt;/a&gt; which is a free, open source network analyzer aka packet sniffer.&lt;/p&gt; &lt;p&gt;WireShark is a great tool and has its own set of extension points, but I wanted lower level access to the packets being captured.  My understanding of the politics and genesis is lacking, but it seems like the &lt;a href="http://www.winpcap.org/" target="_blank"&gt;WinPCap&lt;/a&gt; library is the Windows version of the libpcap packet capture library from the *NIX world.  Naturally, WinPCap is coded in C and even though I have some background in it, the tool I am looking to develop requires a lot of UI work.  Instead of stepping back into the land of MFC/Win32, I tried to locate a Managed version of WinPCap.  The closest thing I could find was this &lt;a href="http://www.codeproject.com/KB/IP/dotnetwinpcap.aspx" target="_blank"&gt;Ancient Project&lt;/a&gt; on CodeProject.com.  It hasn't been updated since 2003 and isn't a "fully" managed wrapper (also, the source code in the download is just to the example, not the wrapper).&lt;/p&gt; &lt;p&gt;I figured, "If this guy can do PInvoke, so can I".  Thus, I downloaded the WinPCap developer pack and attempted to open the example solution in Visual Studio 2008.  Visual Studio 2008 alerted me to the fact that I had to upgrade the project (which was actually a VS 6.0 .dsw file) and I happily agreed.  The upgrade went smooth so I attempted to compile the solution, but received the following error:&lt;/p&gt; &lt;p&gt;&lt;em&gt;&lt;strong&gt;&lt;font color="#ff0000"&gt;"error C3163: '_vsnprintf': attributes inconsistent with previous declaration    c:\program files\Microsoft visual studio 9.0\vc\include\stdio.h    358    savedump"&lt;/font&gt;&lt;/strong&gt;&lt;/em&gt; &lt;/p&gt;&lt;p&gt;Crap. Apparently this is a common problem when compiling older C++ code with the Visual Studio 2008 C++ compiler.  Now, I didn't find a solution for this on the net specific to WinPCap, but several forum posts across other projects lead me to the following solution. &lt;/p&gt;&lt;p&gt;&lt;font&gt;First, find the &lt;strong&gt;pcap-stdinc.h&lt;/strong&gt; file on your system. It should be located in: "...\WpdPack_4_0_2\WpdPack\Include"&lt;/font&gt;&lt;/p&gt; &lt;p&gt;Next, locate the following code near the bottom of your header:&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;#define&lt;/span&gt; snprintf _snprintf
&lt;span style="color: rgb(0,0,255)"&gt;#define&lt;/span&gt; vsnprintf _vsnprintf
&lt;span style="color: rgb(0,0,255)"&gt;#define&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;inline&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;__inline&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;The problem, as we can tell from the compiler error, is that the &lt;strong&gt;"#define vsnprintf _vsnprintf"&lt;/strong&gt; causes some incompatibilities with what is already in stdio.h.  Modify your code to the following and save the header:&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;#define&lt;/span&gt; snprintf _snprintf

&lt;span style="color: rgb(0,0,255)"&gt;#if&lt;/span&gt; !&lt;span style="color: rgb(0,0,255)"&gt;defined&lt;/span&gt;( __MINGW32__ )
&lt;span style="color: rgb(0,0,255)"&gt;# if&lt;/span&gt; _MSC_VER &amp;lt; 1500
&lt;span style="color: rgb(128,128,128)"&gt;    #define vsnprintf _vsnprintf
&lt;/span&gt;&lt;span style="color: rgb(0,0,255)"&gt;# endif
#endif

#define&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;inline&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;__inline&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;You should now be able to compile all the examples in the solution!&lt;/p&gt;
&lt;p&gt;All that we've done is check the version of the compiler at compile time.  If the version is prior to MSC++ 9.0 then we go ahead and do the #define.  Otherwise, we don't do the #define and rely on what is in stdio.h.&lt;/p&gt;
&lt;p&gt;This solution is general in nature, i.e. anything that defines _vsnprintf may exhibit this issue, but specific in the sense that the exact location of the code to modify will vary by project.  In the case of WinPCap, everything is groovy at this point.  Now I just need to learn everything I can about PInvoke : )&lt;/p&gt;&lt;pre class="code"&gt; &lt;/pre&gt; &lt;img src="http://geekswithblogs.net/dotnetnomad/aggbug/119088.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>newman</dc:creator>
            <guid>http://geekswithblogs.net/dotnetnomad/archive/2008/01/30/119088.aspx</guid>
            <pubDate>Wed, 30 Jan 2008 22:52:00 GMT</pubDate>
            <wfw:comment>http://geekswithblogs.net/dotnetnomad/comments/119088.aspx</wfw:comment>
            <comments>http://geekswithblogs.net/dotnetnomad/archive/2008/01/30/119088.aspx#feedback</comments>
            <slash:comments>15</slash:comments>
            <wfw:commentRss>http://geekswithblogs.net/dotnetnomad/comments/commentRss/119088.aspx</wfw:commentRss>
            <trackback:ping>http://geekswithblogs.net/dotnetnomad/services/trackbacks/119088.aspx</trackback:ping>
        </item>
        <item>
            <title>Fun with the WebBrowser Control</title>
            <link>http://geekswithblogs.net/dotnetnomad/archive/2008/01/29/119065.aspx</link>
            <description>&lt;p&gt;   &lt;/p&gt;&lt;div class="wlWriterSmartContent" id="scid:18d43e01-4549-4fde-8ca6-c7b4b7385fac:715c030f-67e5-40cf-a082-6e55d4e688ee" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;p&gt;Download Solution - &lt;a href="http://geekswithblogs.net/images/geekswithblogs_net/dotnetnomad/WindowsLiveWriter/FunwithWebBrowserControl_D203/OfflineHtml_5.zip"&gt;OfflineHtml.zip&lt;/a&gt;&lt;/p&gt;&lt;/div&gt;   &lt;p&gt;So, one of the cool controls available to us in WinForms is System.Windows.Forms.WebBrowser.&lt;/p&gt;  &lt;p&gt;The WebBrowser control is essentially a managed wrapper around some COM interfaces that bind to Internet Explorer and provides us with several interesting capabilities.  First of all, one can use WebBrowser to easily display a web page in a WinForms application.  All you have to do is set the WebBrowser.Url property and the control takes care of getting the assets from across the wire and rendered on the screen.&lt;/p&gt;  &lt;p&gt;WebBrowser also exposes some interesting events that allow a programmer to react when a document is loaded, navigation is peformed, etc.  There are probably a ton of places, including &lt;a href="http://msdn2.microsoft.com/en-us/library/system.windows.forms.webbrowser.aspx" target="_blank"&gt;MSDN&lt;/a&gt;, where you can get that kind of information so I won't go over it here.  Instead, I am going to show something that isn't immediately obvious, but that I believe I found a clean solution to.&lt;/p&gt;  &lt;p&gt; &lt;/p&gt;  &lt;h3&gt;The Task&lt;/h3&gt;  &lt;p&gt;What I want to do is load an HTML page that is on my local computer without causing any network traffic, e.g. it won't load images on the page.  Similar to say, loading a web archive in Internet Explorer.  For our purposes let's use the &lt;a href="http://www.google.com" target="_blank"&gt;Google Home Page&lt;/a&gt; as an example.&lt;/p&gt;  &lt;p&gt; &lt;/p&gt;  &lt;h3&gt;The First Attempt&lt;/h3&gt;  &lt;p&gt;I immediately set upon this task thinking it would be pretty easy.  From what I had gathered on MSDN, after loading a page the WebBrowser control's Document property is populated with an HtmlDocument object.  Similar to System.Xml.XmlDocument, HtmlDocument is a tree like representation of the web page's HTML DOM and it exposes some handy properties for manipulating the HTML elements rendered by the WebBrowser control.  For example, the following code demonstrates setting all of the "src" attributes of the HtmlDocument's img tags to the empty string:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;HtmlDocument&lt;/span&gt; StripImageLoading(&lt;span style="color: rgb(43,145,175)"&gt;HtmlDocument&lt;/span&gt; document)
{

    &lt;span style="color: rgb(0,0,255)"&gt;foreach&lt;/span&gt; (&lt;span style="color: rgb(43,145,175)"&gt;HtmlElement&lt;/span&gt; image &lt;span style="color: rgb(0,0,255)"&gt;in&lt;/span&gt; document.Images)
       image.SetAttribute(&lt;span style="color: rgb(163,21,21)"&gt;"src"&lt;/span&gt;, &lt;span style="color: rgb(0,0,255)"&gt;string&lt;/span&gt;.Empty);
            
    &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; document;

}&lt;/pre&gt;

&lt;p&gt;Iterating over the various HtmlElementCollection objects exposed through HtmlDocument's properties allows one to alter, and even add, HTML elements.  &lt;/p&gt;

&lt;p&gt;This is great, but how do we actually get the WebBrowser control to load an HtmlDocument for us?  There are three primary methods, each of which I'll demonstrate with a code snippet.&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;Setting WebBrowser.Url:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; LoadPage()
{

    &lt;span style="color: rgb(43,145,175)"&gt;WebBrowser&lt;/span&gt; browser = &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;WebBrowser&lt;/span&gt;();
    browser.Url = &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Uri&lt;/span&gt;(&lt;span style="color: rgb(163,21,21)"&gt;"http://www.google.com"&lt;/span&gt;);

}&lt;/pre&gt;

&lt;p&gt;The "primary" way to load a page is to set WebBrowser.Url to a valid Uri object.  When this is done the WebBrowser will get all required data for the page via HTTP and render the results into our HtmlDocument (accessible via the WebBrowser.Document property).&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;Setting WebBrowser.DocumentText:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; LoadPage()
{

    &lt;span style="color: rgb(43,145,175)"&gt;WebBrowser&lt;/span&gt; browser = &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;WebBrowser&lt;/span&gt;();&lt;/pre&gt;

&lt;pre class="code"&gt;    browser.DocumentText = &lt;span style="color: rgb(163,21,21)"&gt;@"&amp;lt;html&amp;gt;&amp;lt;img src=""http://www.domain.com/someimage.gif""&amp;lt;/html&amp;gt;"&lt;/span&gt;;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;pre class="code"&gt;}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;This is the first method that would enable us to achieve our offline viewing goal.  We simply set WebBrowser.DocumentText with a string of HTML and the control uses that to render the page.  The issue with this method is that any HREFs or SRC attributes will be resolved by the WebBrowser control.  In otherwords, in the above example the image file referenced in our &amp;lt;img&amp;gt; tag will actually be downloaded and rendered into the page on the screen.  This, is clearly not what we want.&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;Setting WebBrowser.DocumentStream:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; LoadPage()
{

    &lt;span style="color: rgb(43,145,175)"&gt;WebBrowser&lt;/span&gt; browser = &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;WebBrowser&lt;/span&gt;();
    &lt;span style="color: rgb(43,145,175)"&gt;FileStream&lt;/span&gt; source = &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;FileStream&lt;/span&gt;(&lt;span style="color: rgb(163,21,21)"&gt;@"C:\page.html"&lt;/span&gt;, &lt;span style="color: rgb(43,145,175)"&gt;FileMode&lt;/span&gt;.Open, &lt;span style="color: rgb(43,145,175)"&gt;FileAccess&lt;/span&gt;.Read);

    browser.DocumentStream = source;

}&lt;/pre&gt;

&lt;p&gt;This method allows us to access our page as a Stream.  The WebBrowser control will load the data from the Stream and again, render it into an HtmlDocument object.  Like the DocumentText property, however, it will resolve any HREF or SRC attributes and get the resources from the web.&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;h3&gt;The Hurdle&lt;/h3&gt;

&lt;h3&gt;&lt;/h3&gt;

&lt;p&gt;What we need to do at this point should be clear: we need to some how modify the HtmlDocument prior to the WebBrowser control rendering it on the screen.  I figured there would be an event exposed for this, seemingly obvious, desire.  I looked into the following events, hoping for a quick solution:&lt;/p&gt;

&lt;p&gt;WebBrowser.DocumentCompleted - This event is fired AFTER the page is fully rendered, so it unfortunately doesn't help up.  We can still modify the HtmlDocument at this point, but since any referenced resources have already been downloaded, it is of little value in our situation.&lt;/p&gt;

&lt;p&gt;WebBrowser.ProgressChanged - This event is fired as the page and its resources are being gathered.  It is fired asynchronously, so be very careful when using it.  That being said, I figured initially that I could wait for progress to be 100% and then I'd modify the document.  Unfortunately, this too did not work.&lt;/p&gt;

&lt;p&gt;WebBrowser.FileDownload - Aside from DocumentCompleted, this seemed the most promising.  After all, perhaps I can check to see if the file being downloaded is an image, and if so, simply cancel the download.  No, that won't work because the FileDownload event simply takes an "EventArgs" parameter and therefore gives us no meaningful state on which to operate.&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;So, at this point we have no way of using events to accomplish our task.  We have to find another way.  As most developers do, I scanned the net to find out if this problem had already been cracked.  I didn't find an exact solution, but I did find something that helped at least spark my imagination.  I point you now to the blog of &lt;a href="http://frazzleddad.blogspot.com/2007/07/working-with-webbrowser-control-in.html" target="_blank"&gt;Jim Holmes&lt;/a&gt;.  I kind of know Jim a little from when I lived in Ohio and went to a few Dayton .NET Users Group meetings (of which Jim was/is the President).  Now, Jim is a very smart guy (in fact he has a great &lt;a href="http://www.amazon.com/Windows-Developer-Power-Tools-Turbocharge/dp/0596527543/ref=pd_bbs_sr_1?ie=UTF8&amp;amp;s=books&amp;amp;qid=1201640233&amp;amp;sr=8-1" target="_blank"&gt;O'Reilly Book&lt;/a&gt; out right now) so I'm not sure what happened, but in his article I think he makes a few mistakes about how the WebBrowser control works and I will point those out when we come to them.  Like  I said though, his article at least sparked something in my mind: How do I get an empty HtmlDocument without going through the WebBrowser control?&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;h3&gt;The Solution&lt;/h3&gt;

&lt;p&gt;What we want is to load an HTML page from the local system without causing any actual network traffic.  To make our example more simplistic let's just say we don't want images to load at all.  My solution, for .NET 3.0/3.5 at least, is to introduce an Extension Method for the WebBrowser control that allows us to arbitrarily "filter" the HtmlDocument prior to loading it.  The entire solution is available for download at the beginning of this article, so I've chunked it up a bit for display purposes:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;static&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;class&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;WebBrowserExtensions
&lt;/span&gt;{

    &lt;span style="color: rgb(128,128,128)"&gt;///&lt;/span&gt;&lt;span style="color: rgb(0,128,0)"&gt; &lt;/span&gt;&lt;span style="color: rgb(128,128,128)"&gt;&amp;lt;summary&amp;gt;
&lt;/span&gt;    &lt;span style="color: rgb(128,128,128)"&gt;///&lt;/span&gt;&lt;span style="color: rgb(0,128,0)"&gt; Load an HTML document from a Stream and pass the text through a filter before the page is
&lt;/span&gt;    &lt;span style="color: rgb(128,128,128)"&gt;///&lt;/span&gt;&lt;span style="color: rgb(0,128,0)"&gt; rendered in the WebBrowser control.
&lt;/span&gt;    &lt;span style="color: rgb(128,128,128)"&gt;///&lt;/span&gt;&lt;span style="color: rgb(0,128,0)"&gt; &lt;/span&gt;&lt;span style="color: rgb(128,128,128)"&gt;&amp;lt;/summary&amp;gt;
&lt;/span&gt;    &lt;span style="color: rgb(128,128,128)"&gt;///&lt;/span&gt;&lt;span style="color: rgb(0,128,0)"&gt; &lt;/span&gt;&lt;span style="color: rgb(128,128,128)"&gt;&amp;lt;param name="browser"&amp;gt;&lt;/span&gt;&lt;span style="color: rgb(0,128,0)"&gt;control that renders the filtered HTML&lt;/span&gt;&lt;span style="color: rgb(128,128,128)"&gt;&amp;lt;/param&amp;gt;
&lt;/span&gt;    &lt;span style="color: rgb(128,128,128)"&gt;///&lt;/span&gt;&lt;span style="color: rgb(0,128,0)"&gt; &lt;/span&gt;&lt;span style="color: rgb(128,128,128)"&gt;&amp;lt;param name="source"&amp;gt;&lt;/span&gt;&lt;span style="color: rgb(0,128,0)"&gt;Stream containing the content to filter and render&lt;/span&gt;&lt;span style="color: rgb(128,128,128)"&gt;&amp;lt;/param&amp;gt;
&lt;/span&gt;    &lt;span style="color: rgb(128,128,128)"&gt;///&lt;/span&gt;&lt;span style="color: rgb(0,128,0)"&gt; &lt;/span&gt;&lt;span style="color: rgb(128,128,128)"&gt;&amp;lt;param name="filter"&amp;gt;&lt;/span&gt;&lt;span style="color: rgb(0,128,0)"&gt;Delegate used to filter the source Stream&lt;/span&gt;&lt;span style="color: rgb(128,128,128)"&gt;&amp;lt;/param&amp;gt;
&lt;/span&gt;    &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;static&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; ProcessRequest(&lt;span style="color: rgb(0,0,255)"&gt;this&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;WebBrowser&lt;/span&gt; browser, &lt;span style="color: rgb(43,145,175)"&gt;Stream&lt;/span&gt; source, &lt;span style="color: rgb(43,145,175)"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(43,145,175)"&gt;HtmlDocument&lt;/span&gt;, &lt;span style="color: rgb(43,145,175)"&gt;HtmlDocument&lt;/span&gt;&amp;gt; filter)&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;As we know, Extension Methods must be defined in static classes, as public static members.  You can see the prototype for the ProcessRequest extension about.  It takes two parameters a Stream object that contains the "source" of the page and a delegate that takes an HtmlDocument and returns a modified HtmlDocument.&lt;/p&gt;

&lt;pre class="code"&gt;    &lt;span style="color: rgb(0,0,255)"&gt;using&lt;/span&gt; (&lt;span style="color: rgb(43,145,175)"&gt;WebBrowser&lt;/span&gt; tempBrowser = &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;WebBrowser&lt;/span&gt;())
    {

        &lt;span style="color: rgb(0,128,0)"&gt;//all data from the source as a string
&lt;/span&gt;        &lt;span style="color: rgb(0,0,255)"&gt;string&lt;/span&gt; sourceText = &lt;span style="color: rgb(0,0,255)"&gt;string&lt;/span&gt;.Empty;

        &lt;span style="color: rgb(0,0,255)"&gt;try
&lt;/span&gt;        {

            &lt;span style="color: rgb(0,128,0)"&gt;//read all the data from the source Stream
&lt;/span&gt;            &lt;span style="color: rgb(0,0,255)"&gt;using&lt;/span&gt; (&lt;span style="color: rgb(43,145,175)"&gt;StreamReader&lt;/span&gt; sourceReader = &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;StreamReader&lt;/span&gt;(source))
            {

                sourceText = sourceReader.ReadToEnd();

            }

        }
        &lt;span style="color: rgb(0,0,255)"&gt;catch&lt;/span&gt; (&lt;span style="color: rgb(43,145,175)"&gt;IOException&lt;/span&gt; ex)
        {

            &lt;span style="color: rgb(0,0,255)"&gt;throw&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Exception&lt;/span&gt;(&lt;span style="color: rgb(163,21,21)"&gt;"Could not read data from source stream"&lt;/span&gt;, ex);

        }&lt;/pre&gt;

&lt;p&gt;It is important to note that the WebBrowser control is an absolute resource hog, so please use a using statement or other disposal pattern to property clean it up.  Also, we could have performed all of the operations in this method using the WebBrowser control we were given, but the drawback to that is the control would fire any registered event handlers.  We want our manipulation of the HtmlDocument to be as seamless as possible, and thus we operate on a temporary WebBrowser control.  &lt;/p&gt;

&lt;p&gt;The above chunk of code also performs the mundane task of reading the entire Stream into a string and propagating any exceptions up the stack.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: rgb(0,128,0)"&gt;        //process any text we read from the source Stream
&lt;/span&gt;        &lt;span style="color: rgb(0,0,255)"&gt;if&lt;/span&gt; (!&lt;span style="color: rgb(0,0,255)"&gt;string&lt;/span&gt;.IsNullOrEmpty(sourceText))
        {

            &lt;span style="color: rgb(43,145,175)"&gt;HtmlDocument&lt;/span&gt; tempDocument = &lt;span style="color: rgb(0,0,255)"&gt;null&lt;/span&gt;;
            &lt;span style="color: rgb(43,145,175)"&gt;HtmlElement&lt;/span&gt; htmlRoot = &lt;span style="color: rgb(0,0,255)"&gt;null&lt;/span&gt;;            
            
            &lt;span style="color: rgb(0,128,0)"&gt;//navigate to "about: blank" to initialize an empty document
&lt;/span&gt;            tempBrowser.Navigate(&lt;span style="color: rgb(163,21,21)"&gt;"about: blank"&lt;/span&gt;);&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Now, the above code contains something that Jim tells us to do which is navigate our browser to "about: blank".  As Jim states, correctly, this causes the HtmlDocument object to be created and initially empty.  Exactly what we want, in fact.  However, Jim also seems to imply that this step is always necessary prior to setting either the WebBrowser.DocumentText or WebBrowser.DocumentStream properties.  As the &lt;a href="http://msdn2.microsoft.com/en-us/library/system.windows.forms.webbrowser.documenttext.aspx" target="_blank"&gt;MSDN Documentation&lt;/a&gt; for DocumentText points out, WebBrowser will automatically navigate to "about: blank" each and every time either of these properties is set.&lt;/p&gt;

&lt;p&gt;The reason that we are doing this is that we don't WANT to set DocumentText.  Remember, that will cause all of our resources to be loaded!  All we are trying to do is get an empty HtmlDocument object!&lt;/p&gt;

&lt;pre class="code"&gt;            &lt;span style="color: rgb(0,128,0)"&gt;//load the sourceText into the document.
&lt;/span&gt;            tempBrowser.Document.Write(sourceText);&lt;/pre&gt;

&lt;p&gt;Now that we have navigated to "about: blank", we can use the WebBrowser.Document property to access an empty HtmlDocument.  Further, we can use the HtmlDocument.Write method to populate the document with our HTML.  This is looking pretty nice so far!&lt;/p&gt;

&lt;pre class="code"&gt;            &lt;span style="color: rgb(0,128,0)"&gt;//now filter the document if a filter was specified
&lt;/span&gt;            &lt;span style="color: rgb(0,0,255)"&gt;if&lt;/span&gt;(filter != &lt;span style="color: rgb(0,0,255)"&gt;null&lt;/span&gt;)
                tempDocument = filter(tempBrowser.Document);

            &lt;span style="color: rgb(0,128,0)"&gt;//if the filter did not return a document, or no filter was specified, use the original document
&lt;/span&gt;            &lt;span style="color: rgb(0,0,255)"&gt;if&lt;/span&gt; (tempDocument == &lt;span style="color: rgb(0,0,255)"&gt;null&lt;/span&gt;)
                tempDocument = tempBrowser.Document;&lt;/pre&gt;

&lt;p&gt;The code from here on out is pretty standard.  We are applying any filter we've been given and keeping track of our temporary HtmlDocument object as it is being modified.&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre class="code"&gt;            &lt;span style="color: rgb(0,128,0)"&gt;//find the root HTML element, there can be only one!
&lt;/span&gt;            &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; htmlElements = tempDocument.GetElementsByTagName(&lt;span style="color: rgb(163,21,21)"&gt;"html"&lt;/span&gt;);

            &lt;span style="color: rgb(0,0,255)"&gt;if&lt;/span&gt; (htmlElements != &lt;span style="color: rgb(0,0,255)"&gt;null&lt;/span&gt; &amp;amp;&amp;amp; htmlElements.Count &amp;gt; 0)
                htmlRoot = htmlElements[0];

            &lt;span style="color: rgb(0,128,0)"&gt;//now, extract the text and set it on the actual browser
&lt;/span&gt;            browser.DocumentText = htmlRoot.OuterHtml;&lt;/pre&gt;

&lt;p&gt;To wrap this method up, we get the root &amp;lt;html&amp;gt; tag and then set the WebBrowser.DocumentText property of the WebBrowser control we were given to the &amp;lt;html&amp;gt; tag's OutHtml (i.e. everything in the document including HTML tags and content).&lt;/p&gt;

&lt;p&gt;By setting the DocumentText property, we are forcing the WebBrowser control to load our modified document.  We have accomplished our goal.  We can now modify the HtmlDocument BEFORE it gets rendered.&lt;/p&gt;

&lt;h3&gt;The Final Bits&lt;/h3&gt;

&lt;p&gt;For the sake of completeness, let's use the StripImageLoading method we created earlier to modify a "local" page:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;partial&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;class&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;MainForm&lt;/span&gt; : &lt;span style="color: rgb(43,145,175)"&gt;Form
&lt;/span&gt;{
    &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; MainForm()
    {

        InitializeComponent();

        &lt;span style="color: rgb(0,128,0)"&gt;//get google's home page
&lt;/span&gt;        &lt;span style="color: rgb(43,145,175)"&gt;FileStream&lt;/span&gt; source = &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;FileStream&lt;/span&gt;(&lt;span style="color: rgb(163,21,21)"&gt;@"C:\Development\VS2008\OfflineHtml\google.html"&lt;/span&gt;, &lt;span style="color: rgb(43,145,175)"&gt;FileMode&lt;/span&gt;.Open, &lt;span style="color: rgb(43,145,175)"&gt;FileAccess&lt;/span&gt;.Read);

        &lt;span style="color: rgb(0,128,0)"&gt;//process the request
&lt;/span&gt;        mainBrowser.ProcessRequest(source, StripImageLoading);

    }

    &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;HtmlDocument&lt;/span&gt; StripImageLoading(&lt;span style="color: rgb(43,145,175)"&gt;HtmlDocument&lt;/span&gt; document)
    {

        &lt;span style="color: rgb(0,0,255)"&gt;foreach&lt;/span&gt; (&lt;span style="color: rgb(43,145,175)"&gt;HtmlElement&lt;/span&gt; image &lt;span style="color: rgb(0,0,255)"&gt;in&lt;/span&gt; document.Images)
            image.SetAttribute(&lt;span style="color: rgb(163,21,21)"&gt;"src"&lt;/span&gt;, &lt;span style="color: rgb(0,0,255)"&gt;string&lt;/span&gt;.Empty);
        
        &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; document;

    }

}&lt;/pre&gt;

&lt;p&gt;The above class opens a saved HTML file that contains the source HTML of the Google home page.  It then uses our ProcessRequest extension method to filter the HtmlDocument using the StripImageLoading method as its delegate.  The result when you run the code should be a missing image on the page. If you want to, go download a network analyzer like &lt;a href="http://www.wireshark.org/" target="_blank"&gt;WireShark&lt;/a&gt; to confirm that no HTTP requests are being made as a result of rendering the page.&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;h3&gt;Summary&lt;/h3&gt;

&lt;p&gt;WebBrowser control is pretty cool.  It has a lot of useful features out of the box and is quite extensible.  In this article you've seen its basic usage and a slightly more advanced scenario for which new .NET 3.5 capabilities provide an extremely clean solution.  In fact, it is probably the first time I've really gotten an "Oh yeah! This feels right" when using extension methods outside of LINQ.  Of course, pretty much the same code will compile and work in a .NET 2.0 environment, you'll just have to comment out the "this" modifier in front of the first parameter of the extension method along with any code that uses it, i.e. turn ProcessRequest into a vanilla static method.&lt;/p&gt; &lt;img src="http://geekswithblogs.net/dotnetnomad/aggbug/119065.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>newman</dc:creator>
            <guid>http://geekswithblogs.net/dotnetnomad/archive/2008/01/29/119065.aspx</guid>
            <pubDate>Wed, 30 Jan 2008 04:57:54 GMT</pubDate>
            <wfw:comment>http://geekswithblogs.net/dotnetnomad/comments/119065.aspx</wfw:comment>
            <comments>http://geekswithblogs.net/dotnetnomad/archive/2008/01/29/119065.aspx#feedback</comments>
            <slash:comments>17</slash:comments>
            <wfw:commentRss>http://geekswithblogs.net/dotnetnomad/comments/commentRss/119065.aspx</wfw:commentRss>
            <trackback:ping>http://geekswithblogs.net/dotnetnomad/services/trackbacks/119065.aspx</trackback:ping>
        </item>
        <item>
            <title>LINQ Overview, part two (Lambda Expressions)</title>
            <link>http://geekswithblogs.net/dotnetnomad/archive/2008/01/29/119037.aspx</link>
            <description>&lt;h5&gt;Back Links&lt;/h5&gt;  &lt;p&gt;&lt;a href="http://geekswithblogs.net/dotnetnomad/archive/2007/11/09/116739.aspx"&gt;LINQ Overview, part zero&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://geekswithblogs.net/dotnetnomad/archive/2007/11/12/116793.aspx"&gt;LINQ Overview, part one (Extension Methods)&lt;/a&gt;&lt;/p&gt;  &lt;p&gt; &lt;/p&gt;  &lt;p&gt;&lt;em&gt;NOTE: This article is dedicated to Keith Elder...even if he never sent me a bologna sandwich.&lt;/em&gt;&lt;/p&gt;  &lt;p&gt;Apparently, two months is my definition of "very soon".  Let's continue. &lt;/p&gt;  &lt;p&gt;Since .NET 1.1 we've had the concept of delegates.  They are the constructs that allow us to call methods on objects via reference such as:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;delegate&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;AddFunc&lt;/span&gt;(&lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt; x, &lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt; y);&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;static&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;class&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;MathOps
&lt;/span&gt;{

&lt;span style="color: rgb(0,0,255)"&gt;   public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;static&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt; Add(&lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt; x, &lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt; y)
   {

      &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; x + y;

   }&lt;/pre&gt;

&lt;pre class="code"&gt;} &lt;/pre&gt;

&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;class&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Program
&lt;/span&gt;{&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;   static&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; Main(&lt;span style="color: rgb(0,0,255)"&gt;string&lt;/span&gt;[] args)
   {
           &lt;/pre&gt;

&lt;pre class="code"&gt;&lt;span style="color: rgb(43,145,175)"&gt;      AddFunc&lt;/span&gt; f = &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;AddFunc&lt;/span&gt;(&lt;span style="color: rgb(43,145,175)"&gt;MathOps&lt;/span&gt;.Add);

      &lt;span style="color: rgb(43,145,175)"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: rgb(163,21,21)"&gt;"Delegate: 2 + 2 = {0}"&lt;/span&gt;, f(2, 2));&lt;/pre&gt;

&lt;pre class="code"&gt;      &lt;span style="color: rgb(43,145,175)"&gt;Console&lt;/span&gt;.ReadLine();

   }&lt;/pre&gt;

&lt;pre class="code"&gt;}&lt;/pre&gt;

&lt;p&gt;There is nothing new and exciting about delegates as calling a function via pointer has been around for a very long time.  In fact, delegates are actually somewhat annoying in terms of syntax.  They must be declared in a class, you must wrap them in an object, etc.  Why can't we have a simpler syntax? After all, most of the time delegates are used to respond to relatively simple events or act as part of a strategy pattern (e.g. in a sort).&lt;/p&gt;

&lt;h3&gt;Anonymous Methods&lt;/h3&gt;

&lt;p&gt;In honor of Bill Gates, .NET 2.0 decided to give us a kindler and gentler delegate syntax.  The main method above could easily be rewritten as:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;class&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Program
&lt;/span&gt;{&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;   static&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; Main(&lt;span style="color: rgb(0,0,255)"&gt;string&lt;/span&gt;[] args)
   {
           &lt;/pre&gt;

&lt;pre class="code"&gt;&lt;span style="color: rgb(43,145,175)"&gt;      AddFunc&lt;/span&gt; f = &lt;span style="color: rgb(0,0,255)"&gt;delegate&lt;/span&gt;(&lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt; x, &lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt; y) { &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; x + y; };

      &lt;span style="color: rgb(43,145,175)"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: rgb(163,21,21)"&gt;"Anonymous Method: 2 + 2 = {0}"&lt;/span&gt;, f(2, 2));&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;pre class="code"&gt;      &lt;span style="color: rgb(43,145,175)"&gt;Console&lt;/span&gt;.ReadLine();

   }&lt;/pre&gt;

&lt;pre class="code"&gt;}&lt;/pre&gt;

&lt;p&gt;As is common on the .NET platform the delegate keyword was overloaded to give it additional meaning.  Now one could assign to a delegate variable directly, in the current scope.  The new anonymous method syntax was similar to a method declaration.  The differences are pretty obvious, but I'll list the major ones.  Firstly, anonymous methods don't require identifiers, hence the terms &lt;em&gt;anonymous&lt;/em&gt; methods.  Secondly, anonymous methods do not need to specify a return type.  This is due to some rudimentary type inference built into the compiler.  In essence, if we already know that we are assigning to a delegate of type "AddFunc" whose return type is "int", it should be obvious to the compiler that as long as the return statements in the delegate's body return an "int" then our anonymous delegate matches the signature of "AddFunc".  The counterintuitive aspect of this is that we still have to specify the types of the anonymous method's arguments.  After all, shouldn't the compiler be smart enough to also assume the types of our "x" and "y" based on the delegate type we are assigning to?  It should be, but unfortunately it is not.&lt;/p&gt;

&lt;p&gt;There is something else I want to say about anonymous methods before moving on. This is something I come across all the time and some developers just don't get: anonymous methods allow for lexical closures.  &lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;h3&gt;Lexical Closures&lt;/h3&gt;

&lt;p&gt;There is a lot of bickering on the net about "does .NET support 'true' closures?"  Well, based on my understanding and in my opinion, they support lexical closures or at least something close enough that for most practical purposes it doesn't matter.  I'll leave the 100% correct definition to the language lawyers and just give a quick example and some reasons why a lot of developers get caught in the lexical closure trap.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;delegate&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Increment&lt;/span&gt;();&lt;/pre&gt;

&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;static&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; Main(&lt;span style="color: rgb(0,0,255)"&gt;string&lt;/span&gt;[] args)
{
   &lt;/pre&gt;

&lt;pre class="code"&gt;&lt;span style="color: rgb(43,145,175)"&gt;   Increment&lt;/span&gt; AddOne = AnonInc(0, 1);
   &lt;span style="color: rgb(43,145,175)"&gt;Increment&lt;/span&gt; SubOne = AnonInc(10, -1);

   &lt;span style="color: rgb(0,0,255)"&gt;for&lt;/span&gt; (&lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt; i = 0; i &amp;lt; 10; ++i)
   {

      &lt;span style="color: rgb(43,145,175)"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: rgb(163,21,21)"&gt;"{0},{1}"&lt;/span&gt;, AddOne(), SubOne());

   }&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;pre class="code"&gt;&lt;span style="color: rgb(43,145,175)"&gt;   Console&lt;/span&gt;.ReadLine();&lt;/pre&gt;

&lt;pre class="code"&gt;}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;static&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Increment&lt;/span&gt; AnonInc(&lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt; start, &lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt; by)
{

&lt;span style="color: rgb(0,0,255)"&gt;   return&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;delegate&lt;/span&gt; { &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; start = start + by; };

}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The output of the about code should be:&lt;/p&gt;

&lt;pre class="code"&gt;1,9
2,8
3,7
4,6
5,5,
6,4,
7,3
8,2
9,1
10,0&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;First, take a look at our delegate "Increment".  It takes no arguments and returns an "int".  The idea is that delegates will somehow increment "a value" and return the next value in the sequence.  &lt;/p&gt;

&lt;p&gt;Next, look at the method "AnonInc".  Does it return a delegate? That's crazy!  Further, it returns a delegate that makes use of something commonly referred to as "up values" or "outer variables" depending on the person/system/said person's mood.  An outer variable is simply a variable that exists in the scope that contains the delegate.  In this case, our delegate's scope is the "AnonInc" method in which the "start" and "by" arguments are implicitly defined local variables.  &lt;/p&gt;

&lt;p&gt;Now, based on the definition of the delegate returned by "AnonInc" and the output of the program we can tell something interesting is going on here.  The question you should be asking right now is, "How is it that we are modifying the value of a local variable inside a delegate and it is keeping track of the change?"&lt;/p&gt;

&lt;p&gt;If you recall delegates, and therefore anonymous methods, are represented by objects.  These objects are instances of classes that are automatically generated for you at compile time.  They have funny, mangled names and you can not really do too much with them.  The thing that one needs to know is that any outer variables used by an anonymous delegate become attributes of this auto-generated class.  So, in our case if we look at the assembly generated by the above program using a tool like Reflector we should find a class like:&lt;/p&gt;

&lt;pre class="code"&gt;[CompilerGenerated]
&lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;sealed&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;class&lt;/span&gt; &amp;lt;&amp;gt;c__DisplayClass7
{
    &lt;span style="color: rgb(0,128,0)"&gt;// Fields
&lt;/span&gt;    &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt; by;
    &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt; start;

    &lt;span style="color: rgb(0,128,0)"&gt;// Methods
&lt;/span&gt;    &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt; &amp;lt;AnonInc&amp;gt;b__6()
    {
        &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; (&lt;span style="color: rgb(0,0,255)"&gt;this&lt;/span&gt;.start += &lt;span style="color: rgb(0,0,255)"&gt;this&lt;/span&gt;.by);
    }
}&lt;/pre&gt;

&lt;p&gt;As you can see, the above class has two attributes with the same names as our outer variables and a method that accesses them.  Looking at the code this way kind of takes the magic out of anonymous methods and we being to realize that it is sort of like what I said about extension methods, it is just syntactic sugar.  Handy, but not magical.&lt;/p&gt;

&lt;p&gt;So, what is this trap I was talking about?  Well, it has to do with the garbage collector.  As we all know, in .NET an object lives in memory until it is explicitly disposed of or goes out of scope.  In general perhaps "goes out of scope" is best thought of as "until no other object holds a reference to it".  With lexical closures happening more or less behind the scenes it is very easy to create a memory leak such as the following:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;class&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;ResourceWrapper
&lt;/span&gt;{

    &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; OpenOnClick(&lt;span style="color: rgb(43,145,175)"&gt;Button&lt;/span&gt; btnOpen, &lt;span style="color: rgb(0,0,255)"&gt;string&lt;/span&gt; resourcePath)
    {

        &lt;span style="color: rgb(43,145,175)"&gt;SomeResource&lt;/span&gt; res = &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;SomeResource&lt;/span&gt;(resourcePath);

        btnOpen.Click += &lt;span style="color: rgb(0,0,255)"&gt;delegate&lt;/span&gt;(&lt;span style="color: rgb(0,0,255)"&gt;object&lt;/span&gt; sender, &lt;span style="color: rgb(43,145,175)"&gt;EventArgs&lt;/span&gt; e) { res.Access(); };

    }
    
}

&lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;class&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;SomeResource
&lt;/span&gt;{

    &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; SomeResource(&lt;span style="color: rgb(0,0,255)"&gt;string&lt;/span&gt; path) { }

    &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; Access() { }

}&lt;/pre&gt;

&lt;p&gt;Granted, this example is contrived, but you see similar things all the time.  So, what's going on here? Basically if we look at "OpenOnClick" we can see that an anonymous method is being registered as the Click event for a button.  Further, the anonymous method is using an outer variable "res".  This means that the following class gets generated for us:&lt;/p&gt;

&lt;pre class="code"&gt;[CompilerGenerated]
&lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;sealed&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;class&lt;/span&gt; &amp;lt;&amp;gt;c__DisplayClass1
{
    &lt;span style="color: rgb(0,128,0)"&gt;// Fields
&lt;/span&gt;    &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; SomeResource res;

    &lt;span style="color: rgb(0,128,0)"&gt;// Methods
&lt;/span&gt;    &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; &amp;lt;OpenOnClick&amp;gt;b__0(&lt;span style="color: rgb(0,0,255)"&gt;object&lt;/span&gt; sender, EventArgs e)
    {
        &lt;span style="color: rgb(0,0,255)"&gt;this&lt;/span&gt;.res.Access();
    }
}&lt;/pre&gt;

&lt;p&gt;Normally, we'd just assume that since "res" is a local variable in the "OpenOnClick" method that it'd die as soon as it ran out of scope, i.e. at the end of the method.  However, since our anonymous delegate is holding a reference to it, the object "res" is referencing will live until the anonymous delegate itself goes out of scope.  One can easily see how this kind of situation can go bad quickly.  To avoid this situation, be careful to unregister your anonymous methods when you use them as event handlers!&lt;/p&gt;

&lt;p&gt;Alright, so why did I get into all of this anonymous method stuff if the post is supposed to be about Lambda Expressions? Well, because Lambda Expressions in C# are just an evolutionary step beyond anonymous methods.  Let's chip away at some of the sugar...&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;h3&gt;&lt;/h3&gt;

&lt;h3&gt;&lt;/h3&gt;

&lt;h3&gt;Our first Lambda&lt;/h3&gt;

&lt;p&gt;It is difficult to describe the syntax of a lambda expression since it is very ambiguous and depends on multiple factors.  With that in mind let's look at a quick example:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: rgb(43,145,175)"&gt;AddFunc&lt;/span&gt; f = (x, y) =&amp;gt; x + y;&lt;/pre&gt;

&lt;p&gt;The above snippet declares a new AddFunc delegate and assigns a lambda expression to it.  Everything to the right of the = operator is the lambda definition.  &lt;/p&gt;

&lt;p&gt;Some questions:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Where is the return type? &lt;/li&gt;

  &lt;li&gt;Where is the identifier? &lt;/li&gt;

  &lt;li&gt;Does (x, y) denote the parameter list? &lt;/li&gt;

  &lt;li&gt;What does the =&amp;gt; do? &lt;/li&gt;

  &lt;li&gt;Why isn't there a return statement? &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Some answers:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Lambda expressions do not need an explicit return type.  Just like with anonymous methods the compiler is smart enough to infer the return type based on the type of delegate it is being assigned to. In this case AddFunc returns an int, and so the lambda implicitly returns and int.  Obviously it is a compiler error if the lambda does not. &lt;/li&gt;

  &lt;li&gt;Lambda expressions are by definition anonymous.  They do not have identifiers. &lt;/li&gt;

  &lt;li&gt;Yes.  Further, you should note that lambda parameters do not need to explicitly state their type.  This, like the return type, is inferred by the compiler based on their order compared to the delegate's parameters list. You can, however, state the types explicitly.  (int x, int y) is a valid lambda expression parameter list. &lt;/li&gt;

  &lt;li&gt;The new =&amp;gt; operator is the start of the expression's body.  Everything after =&amp;gt; defines what the lambda expression &lt;em&gt;does&lt;/em&gt;. &lt;/li&gt;

  &lt;li&gt;Lambda expression don't require an explicit return statement.  When a return isn't provided the return value is assumed to be whatever the lambda expression evaluates to. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;So, let's take a look at a few other valid ways to write lambda expressions:&lt;/p&gt;

&lt;pre class="code"&gt;(&lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt; x, &lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt; y) =&amp;gt; { &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; x + y; };&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;The above is the most explicit way.  We've specified types for the parameters and a real return statement.  Notice how when we use an actual return expression we have to use the { } brackets? This same syntax allows us to create multi-line lambdas and lambdas that declare local variables.&lt;/p&gt;

&lt;pre class="code"&gt;(x, y) =&amp;gt; { &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; x + y; };&lt;/pre&gt;

&lt;p&gt;This one keeps the return statement and just drops the optional types in the parameter list.&lt;/p&gt;

&lt;p&gt;() =&amp;gt; x + y;&lt;/p&gt;

&lt;p&gt;In the above, we've specified a lambda with an empty parameter list.  In this case we are assuming the existence of x and y as outer variables (yes, lambda expressions support lexical closures just like anonymous methods).&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;h3&gt;A Lambda is what you assign it to&lt;/h3&gt;

&lt;p&gt;So far we've seen that lambda expressions are compatible with delegates in the sense that you can assign a lambda directly to a delegate, but there are other interesting uses. Take a second and think about writing a program in a text editor.  To the text editor, or for that matter to the compiler, the lines of code your write are just data.  The compiler doesn't execute your program, it simply translates data from one format to another.  It is natural then to ask, "If I can store a program as data, can I load a program as data at run time and then execute it?" With lambda expressions the answer is yes.&lt;/p&gt;

&lt;p&gt;If we assign a lambda expression to a delegate it becomes a delegate of that type.&lt;/p&gt;

&lt;p&gt;If we assign a lambda expression to an appropriately typed Expression Tree it gets converted at compile time to equivalent Expression objects.&lt;/p&gt;

&lt;p&gt;For example:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: rgb(43,145,175)"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(43,145,175)"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt;, &lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt;, &lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt;&amp;gt;&amp;gt; exp = (x, y) =&amp;gt; x + y;&lt;/pre&gt;

&lt;p&gt;This statement simply says, "Convert this lambda expression into an expression tree equivalent to a method that takes two integer parameters and returns the sum as an integer".&lt;/p&gt;

&lt;p&gt;There is no resulting compilation of this tree and no execution of code as a result of this statement.  If at runtime we need to execute the function the tree represents, we must say:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: rgb(43,145,175)"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(43,145,175)"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt;, &lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt;, &lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt;&amp;gt;&amp;gt; exp = (x, y) =&amp;gt; x + y;
&lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; func = exp.Compile();
&lt;span style="color: rgb(43,145,175)"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: rgb(163,21,21)"&gt;"{0}"&lt;/span&gt;, func(1, 1));&lt;/pre&gt;

&lt;p&gt;Now, it isn't inherently obvious why this is cool so I'll spell it out: If the compiler can represent executable code using Expression objects, so can we.  In fact, we will do exactly that by the end of this series.&lt;/p&gt;

&lt;p&gt;As funny as it may sound, this is all you really need to know about lambda expressions.   You can use them in place of anonymous delegates (and you should), they forced the .NET team to provide C# with something approaching real type inference, and they allow us to represent code as data in a statically type checked way.&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;h2&gt;LINQ Tie In&lt;/h2&gt;

&lt;p&gt;Awesome. How are Lambda Expressions useful in LINQ?  Well, by now you've read the basic LINQ syntax somewhere else as I asked so I'll just show a couple of quick examples:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;static&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; UseLINQ()
{

    &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; names = &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(43,145,175)"&gt;GenderedName&lt;/span&gt;&amp;gt; { 
        &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;GenderedName&lt;/span&gt; { Name=&lt;span style="color: rgb(163,21,21)"&gt;"Bob"&lt;/span&gt;, Gender=&lt;span style="color: rgb(43,145,175)"&gt;Gender&lt;/span&gt;.Boy }
        , &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;GenderedName&lt;/span&gt; { Name=&lt;span style="color: rgb(163,21,21)"&gt;"Sally"&lt;/span&gt;, Gender=&lt;span style="color: rgb(43,145,175)"&gt;Gender&lt;/span&gt;.Girl }
        , &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;GenderedName&lt;/span&gt; { Name=&lt;span style="color: rgb(163,21,21)"&gt;"Jack"&lt;/span&gt;, Gender=&lt;span style="color: rgb(43,145,175)"&gt;Gender&lt;/span&gt;.Boy }
        , &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;GenderedName&lt;/span&gt; { Name=&lt;span style="color: rgb(163,21,21)"&gt;"Sarah"&lt;/span&gt;, Gender=&lt;span style="color: rgb(43,145,175)"&gt;Gender&lt;/span&gt;.Girl }
        , &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;GenderedName&lt;/span&gt; { Name=&lt;span style="color: rgb(163,21,21)"&gt;"Philbert"&lt;/span&gt;, Gender=&lt;span style="color: rgb(43,145,175)"&gt;Gender&lt;/span&gt;.Boy }            
    };

    &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; boyNames = names.Where((n) =&amp;gt; n.Gender == &lt;span style="color: rgb(43,145,175)"&gt;Gender&lt;/span&gt;.Boy).Select((n) =&amp;gt; &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; { n.Name });

    &lt;span style="color: rgb(0,0,255)"&gt;foreach&lt;/span&gt; (&lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; name &lt;span style="color: rgb(0,0,255)"&gt;in&lt;/span&gt; boyNames)
        &lt;span style="color: rgb(43,145,175)"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: rgb(163,21,21)"&gt;"{0}"&lt;/span&gt;, name.Name);

}&lt;/pre&gt;

&lt;p&gt;This above function queries a list of names for those that are traditionally used for boys.  In order to make use of the actual lambda expression syntax I used the method based approach to querying with LINQ.  In fact, there are two lambdas in our code:&lt;/p&gt;

&lt;pre class="code"&gt;(n) =&amp;gt; n.Gender == &lt;span style="color: rgb(43,145,175)"&gt;Gender&lt;/span&gt;.Boy&lt;/pre&gt;

&lt;p&gt;This lambda is for our selection criteria and simply compares the given name, n, to see if it is used for boys.  &lt;/p&gt;

&lt;pre class="code"&gt;(n) =&amp;gt; &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; { n.Name }&lt;/pre&gt;

&lt;p&gt;In this expression we are returning a new anonymous type that just contains the Name property of the GenderedName that has passed our selection criteria.&lt;/p&gt;

&lt;p&gt;We can simplify, or rather pretty up, this method by using the new LINQ keywords as so:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;static&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; UseLINQ()
{

    &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; names = &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(43,145,175)"&gt;GenderedName&lt;/span&gt;&amp;gt; { 
        &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;GenderedName&lt;/span&gt; { Name=&lt;span style="color: rgb(163,21,21)"&gt;"Bob"&lt;/span&gt;, Gender=&lt;span style="color: rgb(43,145,175)"&gt;Gender&lt;/span&gt;.Boy }
        , &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;GenderedName&lt;/span&gt; { Name=&lt;span style="color: rgb(163,21,21)"&gt;"Sally"&lt;/span&gt;, Gender=&lt;span style="color: rgb(43,145,175)"&gt;Gender&lt;/span&gt;.Girl }
        , &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;GenderedName&lt;/span&gt; { Name=&lt;span style="color: rgb(163,21,21)"&gt;"Jack"&lt;/span&gt;, Gender=&lt;span style="color: rgb(43,145,175)"&gt;Gender&lt;/span&gt;.Boy }
        , &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;GenderedName&lt;/span&gt; { Name=&lt;span style="color: rgb(163,21,21)"&gt;"Sarah"&lt;/span&gt;, Gender=&lt;span style="color: rgb(43,145,175)"&gt;Gender&lt;/span&gt;.Girl }
        , &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;GenderedName&lt;/span&gt; { Name=&lt;span style="color: rgb(163,21,21)"&gt;"Philbert"&lt;/span&gt;, Gender=&lt;span style="color: rgb(43,145,175)"&gt;Gender&lt;/span&gt;.Boy }            
    };

    &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; boyNames = &lt;span style="color: rgb(0,0,255)"&gt;from&lt;/span&gt; n &lt;span style="color: rgb(0,0,255)"&gt;in&lt;/span&gt; names
                   &lt;span style="color: rgb(0,0,255)"&gt;where&lt;/span&gt; n.Gender == &lt;span style="color: rgb(43,145,175)"&gt;Gender&lt;/span&gt;.Boy
                   &lt;span style="color: rgb(0,0,255)"&gt;select&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; { n.Name };

    &lt;span style="color: rgb(0,0,255)"&gt;foreach&lt;/span&gt; (&lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; name &lt;span style="color: rgb(0,0,255)"&gt;in&lt;/span&gt; boyNames)
        &lt;span style="color: rgb(43,145,175)"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: rgb(163,21,21)"&gt;"{0}"&lt;/span&gt;, name.Name);

}&lt;/pre&gt;

&lt;p&gt;It doesn't look like we are using lambda expressions here, but we really are.  It is just that the compiler needs to turn our pretty code into the same method calls that we just used, and therefore ultimately into an Expression Tree for later execution.&lt;/p&gt;

&lt;p&gt;I just want to be very explicit here and point out something.  When we are using LINQ we use lambda expressions as delegates.  We know this because the parameters of the Where method accept arguments of the Func&amp;lt;T&amp;gt; variety.  The Func series of generic types are actually generic delegates.  For example, MSDN has the following definition for Func&amp;lt;T, TResult&amp;gt;:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;delegate&lt;/span&gt; TResult &lt;span style="color: rgb(43,145,175)"&gt;Func&lt;/span&gt;&amp;lt;T, TResult&amp;gt;(
    T arg
)&lt;/pre&gt;

&lt;p&gt;This usage of delegates and expression trees is what allows LINQ to support Lazy Evaluation.&lt;/p&gt; &lt;img src="http://geekswithblogs.net/dotnetnomad/aggbug/119037.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>newman</dc:creator>
            <guid>http://geekswithblogs.net/dotnetnomad/archive/2008/01/29/119037.aspx</guid>
            <pubDate>Tue, 29 Jan 2008 21:41:15 GMT</pubDate>
            <wfw:comment>http://geekswithblogs.net/dotnetnomad/comments/119037.aspx</wfw:comment>
            <comments>http://geekswithblogs.net/dotnetnomad/archive/2008/01/29/119037.aspx#feedback</comments>
            <slash:comments>17</slash:comments>
            <wfw:commentRss>http://geekswithblogs.net/dotnetnomad/comments/commentRss/119037.aspx</wfw:commentRss>
            <trackback:ping>http://geekswithblogs.net/dotnetnomad/services/trackbacks/119037.aspx</trackback:ping>
        </item>
    </channel>
</rss>
