<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Hungry for Knowledge</title>
	<atom:link href="http://sdesmedt.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://sdesmedt.wordpress.com</link>
	<description>Sometimes the hunger can be so overwhelming it can never be satisfied</description>
	<lastBuildDate>Mon, 28 Sep 2009 17:06:18 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='sdesmedt.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/21177c0c24031c1e7f4cb9d6cfa9d4d7?s=96&#038;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>Hungry for Knowledge</title>
		<link>http://sdesmedt.wordpress.com</link>
	</image>
			<item>
		<title>Offline Maps: Update your base URL’s</title>
		<link>http://sdesmedt.wordpress.com/2009/09/28/offline-maps-update-your-base-url%e2%80%99s-2/</link>
		<comments>http://sdesmedt.wordpress.com/2009/09/28/offline-maps-update-your-base-url%e2%80%99s-2/#comments</comments>
		<pubDate>Mon, 28 Sep 2009 17:06:18 +0000</pubDate>
		<dc:creator>serge desmedt</dc:creator>
				<category><![CDATA[OfflineMaps]]></category>

		<guid isPermaLink="false">http://sdesmedt.wordpress.com/?p=808</guid>
		<description><![CDATA[Google changed the base URL for retrieving tiles, so hit that &#8220;Retrieve&#8221; button in the Offline Maps application to be able to continue to use it.
For those that want to do it manually, see the URL table on the Offline Maps project page
Good luck !!
       <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sdesmedt.wordpress.com&blog=158868&post=808&subd=sdesmedt&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Google changed the base URL for retrieving tiles, so hit that &#8220;Retrieve&#8221; button in the <a href="http://sdesmedt.wordpress.com/offline-maps/">Offline Maps</a> application to be able to continue to use it.</p>
<p>For those that want to do it manually, see the URL table on the <a href="http://sdesmedt.wordpress.com/offline-maps/">Offline Maps project page</a></p>
<p>Good luck !!</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sdesmedt.wordpress.com/808/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sdesmedt.wordpress.com/808/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sdesmedt.wordpress.com/808/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sdesmedt.wordpress.com/808/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sdesmedt.wordpress.com/808/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sdesmedt.wordpress.com/808/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sdesmedt.wordpress.com/808/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sdesmedt.wordpress.com/808/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sdesmedt.wordpress.com/808/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sdesmedt.wordpress.com/808/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sdesmedt.wordpress.com&blog=158868&post=808&subd=sdesmedt&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://sdesmedt.wordpress.com/2009/09/28/offline-maps-update-your-base-url%e2%80%99s-2/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/97a1a6d85466d4f9c0c7fe6baa93478b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sdesmedt</media:title>
		</media:content>
	</item>
		<item>
		<title>About stubs, fakes and mocks</title>
		<link>http://sdesmedt.wordpress.com/2009/09/02/about-stubs-fakes-and-mocks/</link>
		<comments>http://sdesmedt.wordpress.com/2009/09/02/about-stubs-fakes-and-mocks/#comments</comments>
		<pubDate>Wed, 02 Sep 2009 19:35:49 +0000</pubDate>
		<dc:creator>serge desmedt</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[fakes]]></category>
		<category><![CDATA[mocks]]></category>
		<category><![CDATA[stubs]]></category>
		<category><![CDATA[Test driven development]]></category>

		<guid isPermaLink="false">http://sdesmedt.wordpress.com/?p=683</guid>
		<description><![CDATA[Test driven development is not an easy subject. And to be honest, I&#8217;ve not been convinced of it&#8217;s usefullness when first reading about it, witnessing this post. What I do believe firmelly is the usefulness of unit testing. But I have found that overall resistance to unit testing is rather big mostly because if not [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sdesmedt.wordpress.com&blog=158868&post=683&subd=sdesmedt&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Test driven development is not an easy subject. And to be honest, I&#8217;ve not been convinced of it&#8217;s usefullness when first reading about it, witnessing <a href="http://sdesmedt.wordpress.com/2006/07/28/the-practical-traveller/">this post</a>. What I do believe firmelly is the usefulness of unit testing. But I have found that overall resistance to unit testing is rather big mostly because if not done well it turns out to be rather timeconsuming.</p>
<p>Now, let me start by saying I&#8217;m not an expert on the subject. I&#8217;ve tried applying it to some projects with some success and wanted to use it extensively in the next major release of my Offline Maps project. So I did some research to find where I could improve and my first subject was mock objects. </p>
<p>It turned that mocks are only a part of the complete picture.</p>
<h2>Ok mocks, but what about stubs, dummies, fakes, etc&#8230;</h2>
<p>There is a lot of lingo surrounding unit testing. Before we get any deeper on mock objects lets clearly define what they are and more importandly, what they are not and what differentiates them from stubs, fakes, etc&#8230;</p>
<h3>Stubs</h3>
<p>According to <a href="http://codebetter.com/blogs/jeremy.miller/archive/2005/12/19/135757.aspx">Jeremy Miller</a>, the difference between mocks and stubs is mostly in the sort of testing you&#8217;re performing:</p>
<blockquote><p>The real difference between a mock and a stub is in the style of unit testing, i.e. state-based testing versus interaction testing.  A stub is a class that is hard-coded to return data from its methods and properties. You use stubs inside unit tests when you’re testing that a class or method derives the expected output for a known input.</p></blockquote>
<p><a href="http://xunitpatterns.com/Test%20Stub.html">Gerard Meszaros</a> provides a bit more detail:</p>
<blockquote><p>In many circumstances, the environment or context in which the system under test (SUT) operates very much influences the behavior of the SUT. To get good enough control over the indirect inputs of the SUT, we may have to replace some of the context with something we can control, a Test Stub.</p></blockquote>
<p>So, you use stubs if you want to provide data to your system under test and the outcome of your system under test is dependend on the content of that data. A good example would be an object which has as input the current date and for example calculates yesterday. If you where to use the effective current date, then you could never write a test because each different day you execute the test would use a different current day, thus calculate a different yesterday and thus the value against which you want to check would change every day. If you however create a stub which provides a current day that you can set fixed, then you can reproduce the result whenever you want:</p>
<p>An example:</p>
<p>The code we want to test is the following:</p>
<pre class="brush: csharp;">
public ITodayProvider TodayProvider { get; set; }
public DateTime Yesterday
{
	get { return TodayProvider.Today.AddDays(-1); }
}
</pre>
<p>The implementation of ITodayProvider used in the application uses the system date:</p>
<pre class="brush: csharp;">
public DateTime Today
{
	get { return DateTime.Today; }
}
</pre>
<p>The implementation of ITodayProvider used in the test however allows to set the date that will be returned:</p>
<pre class="brush: csharp;">
public DateTime Today
{
	get;
	set;
}
</pre>
<p>The test with the ITodayProvider using the system date does not produce repeatable results:</p>
<pre class="brush: csharp;">
[Test]
public void WithoutStubTest()
{
	CalculateYesterday yesterdayCalculator = new CalculateYesterday();
	yesterdayCalculator.TodayProvider = new TodayProvider();

	// Unless you execute this test exactly on 1st september 2009, this test will fail
	Assert.AreEqual(new DateTime(2009, 8, 31), yesterdayCalculator.Yesterday);
}
</pre>
<p>The test with the ITodayProvider which can be set does allow to produce repeatable results:</p>
<pre class="brush: csharp;">
[Test]
public void WithStubTest()
{
	CalculateYesterday yesterdayCalculator = new CalculateYesterday();
	TodayProviderStub stub = new TodayProviderStub();
	stub.Today = new DateTime(2009, 9, 1);
	yesterdayCalculator.TodayProvider = stub;

	// This test will always succeed, that is if you implementerd the yesterday calculation correctly.
	// It is however completely independent of the day the test is executed
	Assert.AreEqual(new DateTime(2009, 8, 31), yesterdayCalculator.Yesterday);
}
</pre>
<h3>Fakes</h3>
<p>Where a stub actually influences the system undertest, a fake only &#8220;fakes&#8221; an object in the system under test. Again according to <a href="http://xunitpatterns.com/Fake%20Object.html">Gerard Meszaros</a>:</p>
<blockquote><p>The SUT often depend on other components or systems. The interactions with these other components may be necessary but the side-effects of these interactions as implemented by the real depended-on component (DOC), may be unnecessary or even detrimental. A Fake Object is a much simpler and lighter weight implementation of the functionality provided by the DOC without the side effects we choose to do without.</p></blockquote>
<p>Matin Fowler in <a href="http://martinfowler.com/bliki/TestDouble.html">his post on different  kinds of test doubles</a> states  the following:</p>
<blockquote><p>Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production (an InMemoryTestDatabase is a good example) So whereas stubs don&#8217;t have any working functionality, fakes have. They just take some shortcuts. Stubs are typically hardcoded to return some value.</p></blockquote>
<p>As an example, suppose your object uses a webservice for retrieving some values, you may not be interested in setting up a connection to the webservice, provide a connection string, etc&#8230; because the actual webservice used is unimportant to your system under test. You also don&#8217;t want everyone executing your tests to be dependend on the availability of that webservice or detrimental behaviour like unavailable connections, timeouts and all that sort of stuff specific to webservices to mess up your test. In this case you could use a fake in webservice which provides the same functionality but is much easier in setup and which doesn&#8217;t exhibit the unwanted behaviour of unavailable connections and timeouts.</p>
<p>The code we want to test is the following:</p>
<pre class="brush: csharp;">
public ITodayProvider TodayProvider { get; set; }
public IDayRangeCalculatorService DayRangeService { get; set; }
public DateTime YesterdayUsingDayRangeService
{
	get
	{
		IDayRangeCalculator dayRangeCalculator = DayRangeService.ConnectToService();
		int daysBetween = dayRangeCalculator.DaysBetweenTodayAndYesterday();

		return TodayProvider.Today.AddDays(daysBetween);
	}
}
</pre>
<p>A fake implementation of the service allows to get away of all problems relating to connecting to and using of webservices:</p>
<pre class="brush: csharp;">
class DayRangeCalculatorServiceFake : IDayRangeCalculatorService
{
	#region IDayRangeCalculatorService Members

	public IDayRangeCalculator ConnectToService()
	{
		return new DayRangeCalculatorFake();
	}

	#endregion
}

class DayRangeCalculatorFake : IDayRangeCalculator
{
	#region IDayRangeCalculator Members

	public int DaysBetweenTodayAndYesterday()
	{
		return -1;
	}

	#endregion
}
</pre>
<p>By using the fake in the test we know our test will not fail because of problems related to the webservice. So if our test fails, then we know it&#8217;s because our algoritme failed:</p>
<pre class="brush: csharp;">
[Test]
public void WithDaysBetweenServiceFakeTest()
{
	CalculateYesterday yesterdayCalculator = new CalculateYesterday();
	TodayProviderStub stub = new TodayProviderStub();
	stub.Today = new DateTime(2009, 9, 1);
	yesterdayCalculator.TodayProvider = stub;

	yesterdayCalculator.DayRangeService = new DayRangeCalculatorServiceFake();

	// In this test we are only interested if the method returns the correct yesterday
	//  and not if the logging was done correctly
	Assert.AreEqual(new DateTime(2009, 8, 31), yesterdayCalculator.YesterdayWithLogging(new LoggingDummy()));
}
</pre>
<h3>Dummies</h3>
<p>Dummies have no influence at all on the tests. They are just used to provide values for method parameters, etc&#8230;</p>
<p><a href="http://martinfowler.com/bliki/TestDouble.html">Fowler</a>:</p>
<blockquote><p>Dummy objects are passed around but never actually used. Usually they are just used to fill parameter lists.</p></blockquote>
<p>Thus, you use a dummy if you test requires an object which thus not have any influence on the outcome of your test. An example could be a method called in your test which has some specific outcome you want to check but for example also take a logging object as a parameter. Remember we are unit testing and each test checks on some aspect of the object. So we want to check the specific outcome of calling the method but in this test we are not at all interested in the logging of the method. Then we provide a dummy logging object which actually thus nothing but allows us to call the method and check the expected outcome.</p>
<p>The code we want to test is the following:</p>
<pre class="brush: csharp;">
public ITodayProvider TodayProvider { get; set; }

public DateTime YesterdayWithLogging(ILogging logging)
{
	logging.LogMessage(&quot;Executing YesterdayWithLogging&quot;);
	return TodayProvider.Today.AddDays(-1);
}
</pre>
<p>In our test we don&#8217;t care about logging. So we provide a dummy logging class which does nothing:</p>
<pre class="brush: csharp;">
class LoggingDummy:  ILogging
{
	#region ILogging Members

	public void LogMessage(string message)
	{
	}

	#endregion
}
</pre>
<p>In our test we don&#8217;t have to worry about the logging</p>
<pre class="brush: csharp;">
[Test]
public void WithLoggingDummyTest()
{
	CalculateYesterday yesterdayCalculator = new CalculateYesterday();
	TodayProviderStub stub = new TodayProviderStub();
	stub.Today = new DateTime(2009, 9, 1);
	yesterdayCalculator.TodayProvider = stub;

	// In this test we are only interested if the method returns the correct yesterday
	//  and not if the logging was done correctly
	Assert.AreEqual(new DateTime(2009, 8, 31), yesterdayCalculator.YesterdayWithLogging(new LoggingDummy()));
}
</pre>
<p>Now, if all this is a bit overwhelming, don&#8217;t be concerned. Your test doubles will mostly be a mix of the above, or their focus or purpose will shift as shown by Daniel Cazzulino in his post<a href="http://www.clariusconsulting.net/blogs/kzu/archive/2007/12/21/47152.aspx">Mocks, Stubs and Fakes: it&#8217;s a continuum </a>.</p>
<h2>Mock objects, what problems to they solve ?</h2>
<p>In many  posts about the type of test doubles there is also the difference between test spies and mocks. From what I could find on them the difference is not that clear to me. So I will treat them as being the same. Of course, if you can explain the difference in a clear way, you&#8217;re welcome, or if you know a reference let me know.</p>
<h3>About behaviour</h3>
<p>We all know it but lets state it once more explicitely:<br />
Objects are instances of classes which exhibit both state and behaviour. </p>
<p>Anyone studying UML will agree that both the class diagram and the sequence diagram are needed to document the interactions of systems. Where the class diagram shows what properties the classes in the system have, the sequence diagram shows what the important method calls made by the objects are. So you could say that the class diagram documents the state of a system (not entirely thru) and the sequence diagram documents the behaviour of the system. And as you need both the class diagram and the sequence diagram you need both state testing and behaviour testing.</p>
<h3>When to use mock objects</h3>
<p>The main difference with traditional testing is that where traditional testing allows a more state-based approach of testing, mock objects provide a behaviour style of testing. We all know the traditional style of unit testing using frameworks like NUnit, MbUnit and there assert-style testing:</p>
<ol>
<li>Setup your test</li>
<li>Execute some action</li>
<li>Assert that the properties of the object under test are what you expect</li>
</ol>
<p>We assert that the state the object under test is in, is what we expect. To check this state, we check the values of the object&#8217;s properties.</p>
<p>Behaviour style testing on the other hand verifies the dynamic behaviour of the object under test. Remember that we are using mock objects to represent companion objects &#8220;on the edges of the object under test&#8221;. That is, objects used by our object under test. Now, sometimes we will want to know if our object under test calls a certain method with certain arguments of the companion object. The post <a href="http://www.developertesting.com/archives/month200503/20050311-UsingMockObjectsEffectively.html">Using Mock Objects Effectively</a> provides a great example:</p>
<blockquote><p>On closer inspection, it becomes clear that the application is not actually logging anything. Log4J is responsible for doing that. What the application is truly doing is sending a signal (a request) to log4j to log a message. That distinction is *very* important. The appropriate test then is simply to verify that the application is sending the correct signal to the service provider under the right conditions.</p></blockquote>
<p>We now get following test sequence:</p>
<ol>
<li>Setup your test</li>
<li>Execute some action</li>
<li>Assert that the required methods have been executed with the correct parameters and in the correct sequence</li>
</ol>
<p>We assert that the object under test executed the behaviour we expect. To check this behaviour, we check the methods it called and the arguments it provided to those methods.</p>
<p>So, using mock objects for behavioural testing can co-exist with the more traditional style of sate based testing.</p>
<p>Martin Fowler, him again, warns for some caveats when using mock style testing in his article <a href="http://martinfowler.com/articles/mocksArentStubs.html">Mocks Aren&#8217;t Stubs</a>:</p>
<blockquote><p>When you write a mockist test, you are testing the outbound calls of the SUT to ensure it talks properly to its suppliers&#8230;<br />
Coupling to the implementation also interferes with refactoring, since implementation changes are much more likely to break tests than with classic testing.</p></blockquote>
<h3>An example</h3>
<p>The code we want to test is the following:</p>
<pre class="brush: csharp;">
public ITodayProvider TodayProvider { get; set; }

public DateTime YesterdayWithLogging(ILogging logging)
{
	logging.LogMessage(&quot;Executing YesterdayWithLogging&quot;);
	return TodayProvider.Today.AddDays(-1);
}
</pre>
<p>In our test we don&#8217;t care about the exact output of the logging but we do care if the logging is called and if it is called with the correct arguments. So we want to record the methodcall and the arguments with which it got called:</p>
<pre class="brush: csharp;">
class LoggingMock:  ILogging
{
	public int NumberOfMethodCalls { get; private set; }
	public List&lt;String&gt; MethodCallArguments { get; private set; }

	#region ILogging Members

	public void LogMessage(string message)
	{
		NumberOfMethodCalls++;
		if (MethodCallArguments == null)
		{
			MethodCallArguments = new List&lt;string&gt;();
		}

		MethodCallArguments.Add(message);
	}

	#endregion
}
</pre>
<p>By recording the calls we can check in our test if the method got called and if the provided arguments where correct:</p>
<pre class="brush: csharp;">
[Test]
public void WithLoggingMockTest()
{
	CalculateYesterday yesterdayCalculator = new CalculateYesterday();
	TodayProviderStub stub = new TodayProviderStub();
	stub.Today = new DateTime(2009, 9, 1);
	yesterdayCalculator.TodayProvider = stub;
	LoggingMock loggingMock = new LoggingMock();

	// In this test we want to see if the logging is called correctly
	DateTime yesterday = yesterdayCalculator.YesterdayWithLogging(loggingMock);

	Assert.AreEqual(1, loggingMock.NumberOfMethodCalls);
	Assert.AreEqual(&quot;Executing YesterdayWithLogging&quot;, loggingMock.MethodCallArguments[0]);
}
</pre>
<h2>Sample Code</h2>
<p><a>The Code</a></p>
<h2>Links</h2>
<p><a href="http://codebetter.com/blogs/jeremy.miller/archive/2005/12/19/135757.aspx">Mock Objects and Stubs: The Bottle Brush of TDD</a><br />
<a href="http://codebetter.com/blogs/jeremy.miller/archive/2005/12/20/135800.aspx">Why and When to Use Mock Objects</a><br />
<a href="http://codebetter.com/blogs/jeremy.miller/archive/2006/01/10/136407.aspx">Best and Worst Practices for Mock Objects</a><br />
<a href="http://xunitpatterns.com/index.html">xUnit Patterns</a><br />
<a href="http://www.developertesting.com/archives/month200503/20050311-UsingMockObjectsEffectively.html">Using Mock Objects Effectively</a><br />
<a href="http://www.martinfowler.com/bliki/TestDouble.html">MF Bliki: TestDouble</a><br />
<a href="http://martinfowler.com/articles/mocksArentStubs.html">Mocks Aren&#8217;t Stubs</a><br />
<a href="http://en.wikipedia.org/wiki/Mock_object">Mock object</a></p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sdesmedt.wordpress.com/683/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sdesmedt.wordpress.com/683/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sdesmedt.wordpress.com/683/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sdesmedt.wordpress.com/683/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sdesmedt.wordpress.com/683/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sdesmedt.wordpress.com/683/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sdesmedt.wordpress.com/683/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sdesmedt.wordpress.com/683/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sdesmedt.wordpress.com/683/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sdesmedt.wordpress.com/683/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sdesmedt.wordpress.com&blog=158868&post=683&subd=sdesmedt&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://sdesmedt.wordpress.com/2009/09/02/about-stubs-fakes-and-mocks/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/97a1a6d85466d4f9c0c7fe6baa93478b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sdesmedt</media:title>
		</media:content>
	</item>
		<item>
		<title>C# 4.0: Optional Method Parameters</title>
		<link>http://sdesmedt.wordpress.com/2009/07/11/c-4-0-optional-method-parameters/</link>
		<comments>http://sdesmedt.wordpress.com/2009/07/11/c-4-0-optional-method-parameters/#comments</comments>
		<pubDate>Sat, 11 Jul 2009 11:55:57 +0000</pubDate>
		<dc:creator>serge desmedt</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C# 4.0]]></category>

		<guid isPermaLink="false">http://sdesmedt.wordpress.com/?p=787</guid>
		<description><![CDATA[In this first post on new C# language features I will write about Optional Parameters and Named Parameters for methods.
Past and Present
In the current and previous versions of C#, if you wanted to give users of your API the ability to use a method with a different number of parameters you had to overload a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sdesmedt.wordpress.com&blog=158868&post=787&subd=sdesmedt&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>In this first post on new C# language features I will write about Optional Parameters and Named Parameters for methods.</p>
<p><strong>Past and Present</strong></p>
<p>In the current and previous versions of C#, if you wanted to give users of your API the ability to use a method with a different number of parameters you had to overload a method:</p>
<pre class="brush: csharp;">
    public void OldFashionedMethod(string stringParam, int intParam)
    {
      Console.WriteLine(&quot;OldFashionedMethod(two parameters) - The parameters are: stringParameter[{0}] intParameter[{1}]&quot;,
        stringParam, intParam);
    }

    public void OldFashionedMethod(string stringParam)
    {
      int intParam = 8;
      Console.WriteLine(&quot;OldFashionedMethod(one parameter) - The parameters are: stringParameter[{0}] intParameter[{1}]&quot;,
        stringParam, intParam);
    }
</pre>
<p>This allows you to call the method in two ways</p>
<pre class="brush: csharp;">
SomeClass.OldFashionedMethod(&quot;TheParameter&quot;, 10);
SomeClass.OldFashionedMethod(&quot;TheParameter&quot;);
</pre>
<p>You could of course also use <a href="http://articles.techrepublic.com.com/5100-10878_11-1050652.html">this technique</a></p>
<p><strong>Future</strong></p>
<p>In th enext version of C# you will be able to provide default values for the parameters of a method, in the declaration of that method</p>
<pre class="brush: csharp;">
    public void OptionalParameterMethod(string stringParam, int intParam = <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_cool.gif' alt='8)' class='wp-smiley' />
    {
      Console.WriteLine(&quot;The parameters are: stringParameter[{0}] intParameter[{1}]&quot;,
        stringParam, intParam);
    }
</pre>
<p>This also allows you to write similar as above:<br />
This allows you to call the method in two ways</p>
<pre class="brush: csharp;">
SomeClass.OptionalParameterMethod(&quot;TheParameter&quot;, 10);
SomeClass.OptionalParameterMethod(&quot;TheParameter&quot;);
</pre>
<p><strong>If it looks like a duck &#8230;</strong></p>
<p>If we perform the <a href="http://en.wikipedia.org/wiki/Duck_test">Duck test</a> on this code we will come to the conclusion that although the code looks the same, the behaviour is different so both probably aren&#8217;t ducks.</p>
<p>Using <a href="http://www.red-gate.com/products/reflector/">Reflector</a> we can look at how the above is resolved by the compiler:</p>
<p>In the case of overloaded method, the compiler generates the expected method calls, one for each overoaded version:</p>
<pre class="brush: csharp;">
SomeClass.OldFashionedMethod(&quot;TheParameter&quot;, 10);
SomeClass.OldFashionedMethod(&quot;TheParameter&quot;);
</pre>
<p>However, in the case of default parameter values, the compiler generates calls to the single methods and injects the default parameter value when compiling the call making use of the default parameter:</p>
<pre class="brush: csharp;">
SomeClass.OptionalParameterMethod(&quot;TheParameter&quot;, 10);
SomeClass.OptionalParameterMethod(&quot;TheParameter&quot;, 8);
</pre>
<p>So the default parameter is not substituted in the method itself, like it is done when using overloaded methods, but it is resolved at the call site.</p>
<p>In practice this means that when the writer of the library changes the value of the default parameter, your code calling this library will not use this new value, unless you recompile your code.</p>
<p><strong>So, what isn&#8217;t possible?</strong></p>
<p>Optional parameters are only possible at  the end of the parameterlist of a method. So, you can not do the following:</p>
<pre class="brush: csharp;">
public void OptionalParameterMethod(string stringParam = &quot;DefaultValue&quot;, int intParam)
</pre>
<p>From the  above  code you  might wonder why this isn&#8217;t  possible, but have a  look  at the folowing  method  declaration:</p>
<pre class="brush: csharp;">
public void OptionalParameterMethod(string stringParam = &quot;DefaultValue&quot;, string otherStringParam)
</pre>
<p>Now, how must the compiler resolve following  call?</p>
<pre class="brush: csharp;">
SomeClass.OptionalParameterMethod(&quot;TheParameter&quot;);
</pre>
<p>Is the provided parameter a substitute for the default parameter, or is it a value for the last parameter?</p>
<p>Optional parameters can only be compile time constants. This makes the following impossible:</p>
<pre class="brush: csharp;">
public void DefaultClassParameter(ParameterClass param = new ParameterClass())
</pre>
<p>The fact  that only  <a href="http://www.aspnetpro.com/newsletterarticle/2004/05/asp200405bw_l/asp200405bw_l.asp">compile time constants</a> can be used, limits the use of optional parameters to primitive types, enums, or strings.</p>
<p><strong>Usefull or useless</strong></p>
<p>Optional parameters generally generate some of fuss  when discussed because most implemetations  use the  resolve at call site  approach which can produce some unexpected results when the library exposing the method evolves and the default  value changes. <a href="http://stackoverflow.com/questions/940877/extend-an-existing-api-use-default-argument-or-wrapper-function">This article</a> provides some guidance</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sdesmedt.wordpress.com/787/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sdesmedt.wordpress.com/787/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sdesmedt.wordpress.com/787/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sdesmedt.wordpress.com/787/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sdesmedt.wordpress.com/787/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sdesmedt.wordpress.com/787/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sdesmedt.wordpress.com/787/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sdesmedt.wordpress.com/787/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sdesmedt.wordpress.com/787/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sdesmedt.wordpress.com/787/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sdesmedt.wordpress.com&blog=158868&post=787&subd=sdesmedt&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://sdesmedt.wordpress.com/2009/07/11/c-4-0-optional-method-parameters/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/97a1a6d85466d4f9c0c7fe6baa93478b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sdesmedt</media:title>
		</media:content>
	</item>
		<item>
		<title>For once and for all: Delegates, Events, Anonymous Methods and Lambda Expressions</title>
		<link>http://sdesmedt.wordpress.com/2009/05/21/for-once-and-for-all-delegates-events-anonymous-methods-and-lambda-expressions/</link>
		<comments>http://sdesmedt.wordpress.com/2009/05/21/for-once-and-for-all-delegates-events-anonymous-methods-and-lambda-expressions/#comments</comments>
		<pubDate>Thu, 21 May 2009 18:52:52 +0000</pubDate>
		<dc:creator>serge desmedt</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[4O&4A]]></category>
		<category><![CDATA[anonymous methods]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[delegates]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[lambda expressions]]></category>

		<guid isPermaLink="false">http://sdesmedt.wordpress.com/?p=746</guid>
		<description><![CDATA[What started as a simple concept, Delegates and Events, has turned into a major subject in the .NET framework with newcommers like Anonymous Methods and Lambda Expressions. In this post I hope to shed some light on what all these are and how they interact. Mind you however that all that is written in this [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sdesmedt.wordpress.com&blog=158868&post=746&subd=sdesmedt&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>What started as a simple concept, Delegates and Events, has turned into a major subject in the .NET framework with newcommers like Anonymous Methods and Lambda Expressions. In this post I hope to shed some light on what all these are and how they interact. Mind you however that all that is written in this post is not new and has been described in more detail by many other much more smarter people then me. So, allthough I will touch on the various aspects of the subject, for detailed discussions and how certain features work I will forward you to those posts. It is not my goal to repeat what allready has been said, but I wanted investigate what is possible and share my results with you. This way I thought to provide in one post a detailed summary on what is possible and how it&#8217;s done.</p>
<p>It is my hope that after reading this post and reading the referenced articles, one would have an in depth knowledge of delegates, events and the lot.</p>
<p><H1>Delegates</H1></p>
<p>The basic construct for all the above is the delegate. For those familiar with C++: a delegate can be seen as similar to a function pointer in that it allows you to pas a reference to a method around and then later call that method. There are however some differences between them resulting in people trying to <a href="http://www.codeproject.com/KB/cpp/accppdelegates.aspx">emulate delegates in C++</a></p>
<p>For those unfamiliar with C++, <a href="http://stackoverflow.com/questions/399222/i-still-dont-get-delegates/399257#399257">this Stack Overflow article</a> has a nice explanation:</p>
<blockquote><p>The best analogy that I&#8217;ve found to explain delegates it&#8217;s a testament or your last will.</p>
<p>It&#8217;s a set of instructions that of course you write before you die, and you leave it in a safe place. Then after your death, your attorney will execute those instructions&#8230;</p>
<p>Delegates are used mostly when the code that wants to execute the actions doesn&#8217;t knows the enough details of what that action should be, you can view it as a sequence of actions to be executed at the appropriate time.
</p></blockquote>
<p><strong>Declaring a delegate</strong></p>
<p>Declaration of a delegate is done in C# using the <a href="http://msdn.microsoft.com/en-us/library/900fyy8e(VS.80).aspx">delegate</a> keyword:</p>
<pre class="brush: csharp;">
// A delegate is a type of itself, so you
// can declare it outside the scope of a class
delegate int SomeMethodDelegate(string arg);
</pre>
<p>This declaration declares a delegate which can call methods that return an integer and have a string as their single argument. <a href="http://msdn.microsoft.com/en-us/library/system.delegate(VS.80).aspx">A delegate is a type</a> of it&#8217;s own, so a delegate can be declared outside the scope of a class unlike methods and properties. But just as a type (class, struct, &#8230;) can not be declared inside a method, <a href="http://stackoverflow.com/questions/359320/creating-a-delegate-type-inside-a-method">neither can a delegate</a>. If you declare a delegate using the above syntax, you are actually declaring <a href="http://stackoverflow.com/questions/779021/delegate-vs-delegate-keyword-net">a type derived from the Delegate type</a>. Actually, it&#8217;s <a href="http://www.csharphelp.com/archives/archive164.html">derived from</a> the <a href="http://msdn.microsoft.com/en-us/library/system.multicastdelegate.aspx">System.MulticastDelegate</a> type.</p>
<p><strong>Using the delegate</strong></p>
<p><a href="http://msdn.microsoft.com/en-us/library/aa664604(VS.71).aspx">Instantiating the delegate and binding a method</a> to it is as simple as:</p>
<pre class="brush: csharp;">
// Provided you have an object delegateDemo of a class which implements
// a method called MethodCall which takes a string and returns an integer
SomeMethodDelegate delegateReference = new SomeMethodDelegate(delegateDemo.MethodToCall);
</pre>
<p>Using the delegate is similar to invoking the method</p>
<pre class="brush: csharp;">
int i = delegateReference(&quot;String argument&quot;);
</pre>
<p>There is a more longwinded way of instantiating delegates and invoking them directly involving the Delegate class. I will not illustrate it here but you can find more information about it in the Stackoverflow question <a href="http://stackoverflow.com/questions/616018/possible-to-instantiate-and-invoke-a-delegate-by-name">&#8220;Possible to instantiate and invoke a delegate by name?&#8221;</a></p>
<p><strong>Delegates are &#8220;Multicast&#8221;</strong></p>
<p>In the .Net framework, delegates are multicast. What this means is that you can bind more then one method to a delegate:</p>
<pre class="brush: csharp;">
SomeMethodDelegate delegateReference = new SomeMethodDelegate(delegateDemo.MethodToCall);
delegateReference += new SomeMethodDelegate(delegateDemo.SomeOtherMethodToCall);
</pre>
<p>If you now invoke the delegate, the two methods bound to the delegate will be called. If a method in the chain throws an exception, <a href="http://stackoverflow.com/questions/838852/multiple-delegate-attached-and-one-fails">latter methods will no longer be called</a>. You can avoid this by <a href="http://msdn.microsoft.com/en-us/vcsharp/bb508935.aspx">iterating the multicast delegate invocation list yourself</a>.</p>
<p><strong>Life made easy</strong></p>
<p>Delegates are practical beasts and you can use them in lot&#8217;s of places. To help you and to prevent you&#8217;d have to declare new delegate types all over the place, Microsoft declared some delegate types in the .Net Framework which you can use out of the box:</p>
<pre class="brush: csharp;">
Action Delegate
Action&lt;T&gt; Generic Delegate
...
Action&lt;T1, T2, T3, T4&gt; Generic Delegate
</pre>
<p>These encapsulate methods with no return value and zero to 4 arguments.</p>
<p>So, whenever you find the need to write code like</p>
<pre class="brush: csharp;">
delegate void YourDelegate(int, double, string);
YourDelegate yourDelegateInstance;
</pre>
<p>you can instead write:</p>
<pre class="brush: csharp;">
Action&lt;int, double, string&gt; yourDelegateInstance;
</pre>
<pre class="brush: csharp;">
Func&lt;TResult&gt; Generic Delegate
Func&lt;T, TResult&gt; Generic Delegate
...
Func&lt;T1, T2, T3, T4, TResult&gt; Generic Delegate
</pre>
<p>These encapsulate methods with a return type and zero to 4 arguments.</p>
<p>You can find more about predefined delegates <a href="http://stackoverflow.com/questions/729912/standard-delegates-in-c">here</a>.</p>
<p><strong>Deep dive</strong></p>
<p>There is also another, more powerfull, way of instantiating delegates. If you take a look at the MSDN documentation of the Delegate type, then you will see it has a method CreateDelegate which has a number of overriden signatures of which Delegate.CreateDelegate Method (Type, Object, MethodInfo, Boolean) is the most generic one. Where in the above samples the assignment of the delegate also specifies the object to call the method from, with this method it is possible to postpone this decision untill you actually call the instantiated delegate, by providing the object as an argument to the delegate.</p>
<pre class="brush: csharp;">
delegate void OpenMethodDelegate(DelegateDemo target);

class DelegateDemo
{
  public DelegateDemo(string arg)
  {
    m_arg = arg;
  }

  public void MethodToCall()
  {
    Console.Write(&quot;This method got called on object DelegateDemo[&quot; + m_arg + &quot;] using a delegate.\n&quot;);
  }
}

MethodInfo method = typeof(DelegateDemo).GetMethod(&quot;MethodToCall&quot;, BindingFlags.Public | BindingFlags.Instance);
OpenMethodDelegate nonBoundDelegate = (OpenMethodDelegate)Delegate.CreateDelegate(typeof(OpenMethodDelegate), null, method);
DelegateDemo delegateDemo1 = new DelegateDemo(&quot;delegateDemo1&quot;);
nonBoundDelegate(delegateDemo1);
DelegateDemo delegateDemo2 = new DelegateDemo(&quot;delegateDemo2&quot;);
nonBoundDelegate(delegateDemo2);
</pre>
<p>With the above delegate declaration, you can create 4 different delegate instantiations, all documented <a href="http://msdn.microsoft.com/en-us/library/74x8f551.aspx">here</a>. In the sample code with this post you can see an implementation of the 4 possibilities.</p>
<p><H1>Events</H1></p>
<p>Events are technically essentialy the same as delegates, only they have been declared with <a href="http://msdn.microsoft.com/en-us/library/8627sbea(VS.71).aspx">the modifier &#8220;event&#8221;</a>. Thus, they are a special kind of delegate: a <a href="http://msdn.microsoft.com/en-us/library/6tcf2h8w(VS.71).aspx">&#8220;modified&#8221;</a> delegate. However they serve <a href="http://stackoverflow.com/questions/563549/difference-between-events-and-delegates-and-its-respective-applications">a different semantic purpose</a>.</p>
<p><strong>Declaring an event</strong></p>
<p>Because an event is a special kind of instance of a or is <a href="http://blog.monstuff.com/archives/000040.html">a modified delegate</a>, you declare events as a special type of instance of the delegate.</p>
<pre class="brush: csharp;">
delegate int SomeMethodHandler(string arg);
public event SomeMethodHandler SomeMethodEvent;
</pre>
<p>You could compare it with declaring a const:</p>
<pre class="brush: csharp;">
int i;		   // The normal type (in the above this is the delegate)
const int j;	// The modified type (in the above this is the event)
</pre>
<p>The type of modification it does is however completely different. (and then again, it&#8217;s not, but you will read about this further).</p>
<p><strong>Using the delegate as an event</strong></p>
<p>Instantiating the event and binding it to a method is done like:</p>
<pre class="brush: csharp;">
eventDemo.SomethingHappenedEvent += new EventDelegate(eventDemo_SomethingHappenedEvent);
</pre>
<p>Notice how we used the &#8220;+=&#8221; operator instead of the simple assignment operator as done with regular delegates. This is one of the effects of using the event modifier on the delegate. What actually happens when you use the event modifier on a delegate is the following:</p>
<ol>
<li>A field is created on your class with the type of the delegate.</li>
<li>&#8220;Add&#8221; and &#8220;Remove&#8221; <a href="http://stackoverflow.com/questions/623618/what-is-the-definition-of-accessor-method">accessor methods</a> are created to access that field. These two methods are generaly called <a href="http://www.switchonthecode.com/tutorials/csharp-tutorial-event-accessors">&#8220;Event Accessors&#8221;</a></li>
</ol>
<p>This is much in the same way as when you declare <a href="http://stackoverflow.com/questions/219815/if-events-are-implemented-as-delegates-in-net-what-is-the-point-of-the-event-i">a property to access a field</a>. This is also why the above descibes the implementation of what is called <a href="http://msdn.microsoft.com/en-us/library/aa664455.aspx">&#8220;Field like events&#8221;</a>. The above syntax is a C# shortcut for accessing those add and remove handlers.</p>
<p>Using the event-delegate is similar to invoking a method.</p>
<pre class="brush: csharp;">
SomethingHappenedEvent();
</pre>
<p>What is not visible in this code is the fact that this call can only be made inside a method of the class declaring the event. The event field can <a href="http://stackoverflow.com/questions/780022/raise-base-class-events-in-derived-classes-c">not even be accessed in a class deriving from the class declaring the event</a>. This also is an effect of using the event modifier on the delegate instance.</p>
<p>If you want to provide access to derived classes, <a href="http://msdn.microsoft.com/en-us/library/hy3sefw3.aspx">Microsoft suggests declaring so called &#8220;On&#8221; handler methods</a>:</p>
<pre class="brush: csharp;">
event MyCorrectEventHandler MyCorrectEvent;
event EventHandler&lt;MyCorrectEventArgs&gt; TheSameButWithoutTheDelegate;

protected virtual void OnMyCorrectEvent(MyCorrectEventArgs e)
{
  EventHandler&lt;MyCorrectEventArgs&gt; handler = TheSameButWithoutTheDelegate;
  if (handler != null)
  {
    e.SomeValue = 1;
    handler(this, e);
  }
}
</pre>
<p>In the derived class, you then <a href="http://stackoverflow.com/questions/537524/what-is-the-preferred-method-for-event-handling-in-c">raise the event by calling this On&#8230; method</a>.</p>
<p><strong>The &#8220;event&#8221; modifier: what does it do?</strong></p>
<p>The event keyword in C# is actually a modifier on the delegate type. What it modifies is the visibility of certain members of the delegate so that effectively you can <a href="http://stackoverflow.com/questions/213638/how-do-c-events-work-behind-the-scenes#213651">only access the Combine and Remove methods of the Delegate type</a>, that being the reason why you can only add or remove delegate handlers.</p>
<p><strong>Some conventions</strong></p>
<p>The above code, allthough correct, is not the common way of using events. Microsoft provides some guidelines on how to declare and use event in the .NET Framework:</p>
<ul>
<li>The delegate for the event has no return value.</li>
<li>The delegate for the event always has two parameters, the first of type object and referencing the object that fires the event, and the second an EventArgs derived class which identifies details of the event.</li>
</ul>
<p>In the above you will probably recognize the typical eventhandler signature from windows forms:</p>
<pre class="brush: csharp;">
void button_ClickHandler(object sender, System.EventArgs e)
</pre>
<p><strong>Life made easy</strong></p>
<p>When make heavy use of events in your code, you will find yourself declaring lots of events. That would require you to also write lots of delegates for those events, all with this same basic structure of a method taking an object and a EventArgs derived class.</p>
<p>To make life easier Microsoft provides two delegate for you to prevent this clutter:</p>
<pre class="brush: csharp;">
EventHandler Delegate
EventHandler&lt;TEventArgs&gt; Generic Delegate
</pre>
<p>So instead of having to write</p>
<pre class="brush: csharp;">
delegate void MyPersonalEventHandler(object sender, EventArgs e);
event MyPersonalEventHandler MyPersonalEvent;
</pre>
<p>You can now write</p>
<pre class="brush: csharp;">
event EventHandler MyPersonalEvent;
</pre>
<p>Or if you have your own event arguments:</p>
<pre class="brush: csharp;">
class YourEventArgs : EventArgs {... }
event EventHandler&lt;YourEventArgs&gt; YourEventWithSpecialArguments;
</pre>
<p><strong>Deep dive</strong><br />
The above illustrates the most common way of using the event modifier on delegates. If you look at the documentation for the event modifier you will notice that there is also the possibility of declaring events as virtual, abstract, etc&#8230; Whereas the event modifier changes the visibility of certain  members of the delegate, declaring an event as virtual or abstract actually changes the the implementation of the event much in the same way as declaring a property as virtual or abstract.</p>
<p>Just as a abstract or virtual properties provide just the signature for the property getter and setter methods, an abstract or virtual event provides just the signature for the event &#8220;add-er&#8221; and &#8220;remove-er&#8221; methods.</p>
<p>You can then provide your own implementations for the event accessor methods. Being able to provide your own accessor methods implementations is however not a privilege for abstract and virtual events, but can be <a href="http://msdn.microsoft.com/en-us/magazine/cc163533.aspx">done for every event</a>.</p>
<p>Again, in the sample code you can see an implementation of this.</p>
<p><H1>Anonymous methods</H1></p>
<p>Since C# 2.0 there is a new syntax for attaching methods to delegates named <a href="http://msdn.microsoft.com/en-us/library/0yw3tz5k(VS.80).aspx">Anonymous methods</a>. Well, this is actally an over-simplification of anonymous methods. But let&#8217;s stick with this simplification for a minute.</p>
<p><strong>Declaring an anonymous method</strong></p>
<p>In the Delegate section you learned that attaching a method to a delegate is done by creating the method in a class first and then  assigning that method to the delegate:</p>
<pre class="brush: csharp;">
delegate int SomeMethodDelegate(string arg);

class ClassWithMethod
{
   int MethodToCall(string arg) { ... }
}

SomeMethodDelegate delegateReference = new SomeMethodDelegate(delegateDemo.MethodToCall);
</pre>
<p>This can be cumbersome because it obligates you to create a method in a class which you will not always want to do. So C# 2.0 provides you the possibility to declare that method inline with the assignment to the delegate:</p>
<pre class="brush: csharp;">
SomeMethodDelegate d = delegate(string param) { Console.WriteLine(&quot;Param: &quot; + param.ToString()); };
d(&quot;A Parameter&quot;);
</pre>
<p>This can be very handy in certain situations like <a href="http://weblogs.asp.net/dwahlin/archive/2007/04/23/The-Power-of-Anonymous-Methods-in-C_2300_.aspx">sorting of items in a list</a>.</p>
<p><strong>Deep dive</strong></p>
<p>Now why is this an oversimplification? Because with the syntax of Anonymous Methods comes a programming construct more generaly known as <a href="http://en.wikipedia.org/wiki/Closure_(computer_science)">Closures</a> to C#.</p>
<p>What closures allow you to do is <a href="http://www.codeproject.com/KB/cs/InsideAnonymousMethods.aspx">use the variables known in the scope declaring the anonymous method, inside the anonymous method</a>. As an example:</p>
<pre class="brush: csharp;">
public static void UsingLocal()
{
  int i;
  i = 1;
  Action d = delegate(int param) { Console.WriteLine(&quot;With Parameters[&quot; + param.ToString() + &quot;] and Local[&quot; + i.ToString() + &quot;]&quot;); };
  d(2);
}
</pre>
<p>This even extends to the fields of the class in which the declaring scope resides:</p>
<pre class="brush: csharp;">
class AnonymousMethodDeepDive
{
  private int m_field;

  public AnonymousMethodDeepDive(int field)
  {
    m_field = field;
  }

  public int Property { get; set; }

  public void UsingField()
  {
    Action d = delegate(int param) { Console.WriteLine(&quot;With Parameters[&quot; + param.ToString() + &quot;] and Field[&quot; + m_field.ToString() + &quot;]&quot;); };
    d(1);
  }

  public void UsingProperty()
  {
    Action d = delegate(int param) { Console.WriteLine(&quot;With Parameters[&quot; + param.ToString() + &quot;] and Property[&quot; + Property.ToString() + &quot;]&quot;); };
    d(1);
  }
}
</pre>
<p>What essentialy happens is:</p>
<ol>
<li>The compiler generates a class, capturing all the local variables as proeprties of that class.</li>
<li>The compiler generated class has as a method the anonymous method, thus making it&#8217;s properties (and thus tha variables in the decalring scope) available to the anonymous method.</li>
</ol>
<p>There are a few optimizations in some special cases, but the above is the most generic way to look at these.</p>
<p>Now, if you think you understand all this, then read <a href="http://blogs.msdn.com/oldnewthing/archive/2006/08/02/686456.aspx">these</a> two <a href="http://blogs.msdn.com/oldnewthing/archive/2006/08/03/687529.aspx">posts</a>.</p>
<p><H1>Lambda Expressions</H1></p>
<p>Lambda Expressons are in their most basic form a more convenient syntax for anonymous methods. Again, their is a lot more to lambda expressions then this, but <a href="http://stackoverflow.com/questions/208381/whats-the-difference-between-anonymous-methods-c-2-0-and-lambda-expressions">those features</a> have nothing to do with delegates so I will not discuss them in this post.</p>
<p><strong>Syntax</strong></p>
<p>The most generic way for writing lambda expressions is:</p>
<pre class="brush: csharp;">
Func f1 = (int x, string y) =&amp;gt; { Console.WriteLine(&quot;A Return Value And Two Parameters: &quot; + x.ToString()); return x + 1; };
</pre>
<p>In this assignment statement the form</p>
<p>   () =&gt; {  }</p>
<p>is the lambda expression.</p>
<p>Now, there are a few simplifications possible:</p>
<p>Because C# supports parameter type inference, you can drop the type specifiers for the arguments:</p>
<pre class="brush: csharp;">
Func f1 = (x, y) =&gt; { Console.WriteLine(&quot;A Return Value And Two Parameters: &quot; + x.ToString()); return x + 1; };
</pre>
<p>If you have a single statement, you can drop the curly braces and the semicolon:</p>
<pre class="brush: csharp;">
Action d4 = (x, y, z) =&gt; Console.WriteLine(&quot;Three Parameters: [{0}][{1}][{2}]&quot;, x, y, z);
</pre>
<p>If you have a single parameter, you can drop the parameter braces:</p>
<pre class="brush: csharp;">
Action d2 = x =&gt; { Console.WriteLine(&quot;One Parameter: &quot; + x.ToString()); };
</pre>
<p>If you have a single statement, which is the return value, you can drop the &#8220;return&#8221; keyword:</p>
<pre class="brush: csharp;">
Func f2 = x =&gt; x + 1;
</pre>
<h1>Code</h1>
<p>You can download the code <a href="http://www.box.net/shared/qajcsoun5k">here</a></p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sdesmedt.wordpress.com/746/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sdesmedt.wordpress.com/746/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sdesmedt.wordpress.com/746/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sdesmedt.wordpress.com/746/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sdesmedt.wordpress.com/746/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sdesmedt.wordpress.com/746/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sdesmedt.wordpress.com/746/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sdesmedt.wordpress.com/746/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sdesmedt.wordpress.com/746/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sdesmedt.wordpress.com/746/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sdesmedt.wordpress.com&blog=158868&post=746&subd=sdesmedt&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://sdesmedt.wordpress.com/2009/05/21/for-once-and-for-all-delegates-events-anonymous-methods-and-lambda-expressions/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/97a1a6d85466d4f9c0c7fe6baa93478b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sdesmedt</media:title>
		</media:content>
	</item>
		<item>
		<title>Offline Maps: Version 1.4.3</title>
		<link>http://sdesmedt.wordpress.com/2009/05/07/offline-maps-version-143/</link>
		<comments>http://sdesmedt.wordpress.com/2009/05/07/offline-maps-version-143/#comments</comments>
		<pubDate>Thu, 07 May 2009 19:17:53 +0000</pubDate>
		<dc:creator>serge desmedt</dc:creator>
				<category><![CDATA[OfflineMaps]]></category>

		<guid isPermaLink="false">http://sdesmedt.wordpress.com/?p=736</guid>
		<description><![CDATA[New version available at Codeplex
It solves two bugs:

Crash when starting mobile version
Hangs when downloading at excessive zoomfactor

Go check it out.
       <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sdesmedt.wordpress.com&blog=158868&post=736&subd=sdesmedt&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>New version available at <a href="http://offlinemaps.codeplex.com/">Codeplex</a></p>
<p>It solves two bugs:</p>
<ol>
<li><a href="http://sdesmedt.wordpress.com/offline-maps/#comment-3646">Crash when starting mobile version</a></li>
<li><a href="http://sdesmedt.wordpress.com/offline-maps/#comment-3623">Hangs when downloading at excessive zoomfactor</a></li>
</ol>
<p>Go check it out.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sdesmedt.wordpress.com/736/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sdesmedt.wordpress.com/736/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sdesmedt.wordpress.com/736/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sdesmedt.wordpress.com/736/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sdesmedt.wordpress.com/736/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sdesmedt.wordpress.com/736/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sdesmedt.wordpress.com/736/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sdesmedt.wordpress.com/736/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sdesmedt.wordpress.com/736/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sdesmedt.wordpress.com/736/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sdesmedt.wordpress.com&blog=158868&post=736&subd=sdesmedt&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://sdesmedt.wordpress.com/2009/05/07/offline-maps-version-143/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/97a1a6d85466d4f9c0c7fe6baa93478b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sdesmedt</media:title>
		</media:content>
	</item>
		<item>
		<title>Birth of a project: DxFluentUI</title>
		<link>http://sdesmedt.wordpress.com/2009/04/25/birth-of-a-project-dxfluentui/</link>
		<comments>http://sdesmedt.wordpress.com/2009/04/25/birth-of-a-project-dxfluentui/#comments</comments>
		<pubDate>Fri, 24 Apr 2009 22:50:15 +0000</pubDate>
		<dc:creator>serge desmedt</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://sdesmedt.wordpress.com/?p=712</guid>
		<description><![CDATA[I&#8217;ve just started a new project on Codeplex: DxFluentUI.
The goal of the project is to provide a fluent API for the creation of DevExpress controls. It currently provides an incomplete implementation for the XtraGrid and XtraVerticalGrid controls. 
Look back for further details&#8230;.
       <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sdesmedt.wordpress.com&blog=158868&post=712&subd=sdesmedt&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>I&#8217;ve just started a new project on Codeplex: <a href="http://dxfluentui.codeplex.com/">DxFluentUI</a>.</p>
<p>The goal of the project is to provide a fluent API for the creation of DevExpress controls. It currently provides an incomplete implementation for the XtraGrid and XtraVerticalGrid controls. </p>
<p>Look back for further details&#8230;.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sdesmedt.wordpress.com/712/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sdesmedt.wordpress.com/712/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sdesmedt.wordpress.com/712/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sdesmedt.wordpress.com/712/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sdesmedt.wordpress.com/712/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sdesmedt.wordpress.com/712/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sdesmedt.wordpress.com/712/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sdesmedt.wordpress.com/712/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sdesmedt.wordpress.com/712/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sdesmedt.wordpress.com/712/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sdesmedt.wordpress.com&blog=158868&post=712&subd=sdesmedt&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://sdesmedt.wordpress.com/2009/04/25/birth-of-a-project-dxfluentui/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/97a1a6d85466d4f9c0c7fe6baa93478b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sdesmedt</media:title>
		</media:content>
	</item>
		<item>
		<title>What did we learn this week? Week of 13 april 2009</title>
		<link>http://sdesmedt.wordpress.com/2009/04/20/what-did-we-learn-this-week-week-of-13-april-2009/</link>
		<comments>http://sdesmedt.wordpress.com/2009/04/20/what-did-we-learn-this-week-week-of-13-april-2009/#comments</comments>
		<pubDate>Mon, 20 Apr 2009 19:31:23 +0000</pubDate>
		<dc:creator>serge desmedt</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[WDWL]]></category>
		<category><![CDATA[databinding]]></category>
		<category><![CDATA[visual studio installation]]></category>
		<category><![CDATA[windows forms]]></category>

		<guid isPermaLink="false">http://sdesmedt.wordpress.com/?p=705</guid>
		<description><![CDATA[links for this week:
unit testing windows forms applications and more perticular: databinding
While working on some code which encapsulates windows forms controls, I had to check if my abstraction works. And especially, if the databinding works:
 Unit Testing WinForms 2.0 Databinding
Adding features to Visual Studio 2008
It had happened to me before but this time I had [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sdesmedt.wordpress.com&blog=158868&post=705&subd=sdesmedt&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>links for this week:</p>
<p><strong>unit testing windows forms applications and more perticular: databinding</strong><br />
While working on some code which encapsulates windows forms controls, I had to check if my abstraction works. And especially, if the databinding works:<br />
<a href="http://blog.vorpal.cc/category/development/unit-testing-winforms-20-databinding.html"> Unit Testing WinForms 2.0 Databinding</a></p>
<p><strong>Adding features to Visual Studio 2008</strong><br />
It had happened to me before but this time I had to succeed: I needed to install the crystal report features which are part of visual studio. Unfortunately, starting the setup form the dvd failed with the error: &#8220;A problem has been encountered while loading the setup components. Canceling setup.&#8221; After some research following post helped me (make sure you read it until the end):<br />
<a href="http://blogs.msdn.com/heaths/archive/2008/10/06/adding-features-to-visual-studio-2008-may-fail-to-load-setup-components.aspx">Adding features to Visual Studio 2008 may fail to load setup components</a></p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sdesmedt.wordpress.com/705/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sdesmedt.wordpress.com/705/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sdesmedt.wordpress.com/705/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sdesmedt.wordpress.com/705/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sdesmedt.wordpress.com/705/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sdesmedt.wordpress.com/705/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sdesmedt.wordpress.com/705/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sdesmedt.wordpress.com/705/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sdesmedt.wordpress.com/705/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sdesmedt.wordpress.com/705/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sdesmedt.wordpress.com&blog=158868&post=705&subd=sdesmedt&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://sdesmedt.wordpress.com/2009/04/20/what-did-we-learn-this-week-week-of-13-april-2009/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/97a1a6d85466d4f9c0c7fe6baa93478b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sdesmedt</media:title>
		</media:content>
	</item>
		<item>
		<title>Put an “N” in front of it, or add “.NET” to the back. Part I</title>
		<link>http://sdesmedt.wordpress.com/2009/03/09/put-an-%e2%80%9cn%e2%80%9d-in-front-of-it-or-add-%e2%80%9cnet%e2%80%9d-to-the-back-part-i/</link>
		<comments>http://sdesmedt.wordpress.com/2009/03/09/put-an-%e2%80%9cn%e2%80%9d-in-front-of-it-or-add-%e2%80%9cnet%e2%80%9d-to-the-back-part-i/#comments</comments>
		<pubDate>Mon, 09 Mar 2009 21:06:55 +0000</pubDate>
		<dc:creator>serge desmedt</dc:creator>
				<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">http://sdesmedt.wordpress.com/?p=678</guid>
		<description><![CDATA[Thats been a long time:

NPOI &#60;-&#62; Apache POI
Poi.Net &#60;-&#62; Apache POI

For other projects, see:

Put an “N” in front of it, or add “.NET” to the back. Part I
Put an “N” in front of it, or add “.NET” to the back. Part II
Put an “N” in front of it, or add “.NET” to the back. Part [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sdesmedt.wordpress.com&blog=158868&post=678&subd=sdesmedt&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Thats been a long time:</p>
<ul>
<li><a href="http://npoi.codeplex.com/">NPOI</a> &lt;-&gt; <a href="http://poi.apache.org/">Apache POI</a></li>
<li><a href="http://developer.novell.com/wiki/index.php/Poi.Net">Poi.Net</a> &lt;-&gt; <a href="http://poi.apache.org/">Apache POI</a></li>
</ul>
<p>For other projects, see:</p>
<ul>
<li><a href="http://sdesmedt.wordpress.com/2006/05/29/put-an-n-in-front-of-it-or-add-net-to-the-back/">Put an “N” in front of it, or add “.NET” to the back. Part I</a></li>
<li><a href="http://sdesmedt.wordpress.com/2006/06/07/put-an-%e2%80%9cn%e2%80%9d-in-front-of-it-or-add-%e2%80%9cnet%e2%80%9d-to-the-back-part-ii/">Put an “N” in front of it, or add “.NET” to the back. Part II</a></li>
<li><a href="http://sdesmedt.wordpress.com/2006/07/30/put-an-%e2%80%9cn%e2%80%9d-in-front-of-it-or-add-%e2%80%9cnet%e2%80%9d-to-the-back-part-iii/">Put an “N” in front of it, or add “.NET” to the back. Part III</a></li>
<li><a href="http://sdesmedt.wordpress.com/2006/11/25/put-an-%e2%80%9cn%e2%80%9d-in-front-of-it-or-add-%e2%80%9cnet%e2%80%9d-to-the-back-part-iv/">Put an “N” in front of it, or add “.NET” to the back. Part IV</a></li>
</ul>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sdesmedt.wordpress.com/678/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sdesmedt.wordpress.com/678/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sdesmedt.wordpress.com/678/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sdesmedt.wordpress.com/678/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sdesmedt.wordpress.com/678/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sdesmedt.wordpress.com/678/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sdesmedt.wordpress.com/678/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sdesmedt.wordpress.com/678/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sdesmedt.wordpress.com/678/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sdesmedt.wordpress.com/678/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sdesmedt.wordpress.com&blog=158868&post=678&subd=sdesmedt&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://sdesmedt.wordpress.com/2009/03/09/put-an-%e2%80%9cn%e2%80%9d-in-front-of-it-or-add-%e2%80%9cnet%e2%80%9d-to-the-back-part-i/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/97a1a6d85466d4f9c0c7fe6baa93478b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sdesmedt</media:title>
		</media:content>
	</item>
		<item>
		<title>Offline Maps: Version 1.4.2.0 and update of the base URL’s</title>
		<link>http://sdesmedt.wordpress.com/2009/03/08/offline-maps-version-1420-and-update-of-the-base-url%e2%80%99s/</link>
		<comments>http://sdesmedt.wordpress.com/2009/03/08/offline-maps-version-1420-and-update-of-the-base-url%e2%80%99s/#comments</comments>
		<pubDate>Sun, 08 Mar 2009 13:48:56 +0000</pubDate>
		<dc:creator>serge desmedt</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[OfflineMaps]]></category>

		<guid isPermaLink="false">http://sdesmedt.wordpress.com/?p=673</guid>
		<description><![CDATA[I finally got to posting my code on the codeplex website. You can find it here.
The project page on this blog will remain the main source of information about features of the application and how to use it. The codeplex site will however become the reference for the binaries and soucecode. No updates will be [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sdesmedt.wordpress.com&blog=158868&post=673&subd=sdesmedt&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>I finally got to posting my code on the codeplex website. You can find it <a href="http://offlinemaps.codeplex.com/">here</a>.</p>
<p>The project page on this blog will remain the main source of information about features of the application and how to use it. The codeplex site will however become the reference for the binaries and soucecode. No updates will be posted anymore on Box.net</p>
<p>So, without any further ado: go to the codeplex projectpage and download the application on the <a href="http://offlinemaps.codeplex.com/Release/ProjectReleases.aspx#ReleaseFiles">Releases</a> page. People wanting to investigate the sourcecode can find it on the <a href="http://offlinemaps.codeplex.com/SourceControl/ListDownloadableCommits.aspx">Source code</a> page.</p>
<p>First thing to do is to update the base-url. For information on how to do this, visit <a href="http://sdesmedt.wordpress.com/offline-maps/">this</a> page.</p>
<p>Enjoy!</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sdesmedt.wordpress.com/673/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sdesmedt.wordpress.com/673/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sdesmedt.wordpress.com/673/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sdesmedt.wordpress.com/673/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sdesmedt.wordpress.com/673/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sdesmedt.wordpress.com/673/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sdesmedt.wordpress.com/673/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sdesmedt.wordpress.com/673/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sdesmedt.wordpress.com/673/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sdesmedt.wordpress.com/673/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sdesmedt.wordpress.com&blog=158868&post=673&subd=sdesmedt&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://sdesmedt.wordpress.com/2009/03/08/offline-maps-version-1420-and-update-of-the-base-url%e2%80%99s/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/97a1a6d85466d4f9c0c7fe6baa93478b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sdesmedt</media:title>
		</media:content>
	</item>
		<item>
		<title>Unit Of Work Pattern</title>
		<link>http://sdesmedt.wordpress.com/2009/02/18/unit-of-work-pattern/</link>
		<comments>http://sdesmedt.wordpress.com/2009/02/18/unit-of-work-pattern/#comments</comments>
		<pubDate>Wed, 18 Feb 2009 20:56:54 +0000</pubDate>
		<dc:creator>serge desmedt</dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[oop]]></category>
		<category><![CDATA[unit of work]]></category>
		<category><![CDATA[uow]]></category>

		<guid isPermaLink="false">http://sdesmedt.wordpress.com/?p=648</guid>
		<description><![CDATA[I&#8217;ve done some research on the  Unit Of Work pattern and this post will show you what I&#8217;ve learned.
Definition
A short version of the official definition of the term &#8220;Unit Of Work&#8221; can be  found on Martin Fowler&#8217;s website. A longer version can be found here.
Implementation
A small proof of concept type of implementation can [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sdesmedt.wordpress.com&blog=158868&post=648&subd=sdesmedt&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>I&#8217;ve done some research on the  Unit Of Work pattern and this post will show you what I&#8217;ve learned.</p>
<p><strong>Definition</strong></p>
<p>A short version of the official definition of the term &#8220;Unit Of Work&#8221; can be  found on <a href="http://martinfowler.com/eaaCatalog/unitOfWork.html">Martin Fowler&#8217;s website</a>. A longer version can be found <a href="http://takacsot.freeblog.hu/Files/martinfowler/unitOfWork.html">here</a>.</p>
<p><strong>Implementation</strong><br />
A small proof of concept type of implementation can be found at <a href="http://www.codeinsanity.com/2008/09/unit-of-work-pattern.html">Code Insanity: The Unit of Work Pattern</a>.  He continuous in his post <a href="http://www.codeinsanity.com/2008/10/implementing-persistence-ignorant-unit.html">Implementing a persistence ignorant Unit of Work framework</a>.</p>
<p>Looking around the internet for information you will often find remarks about the Unit Of Work pattern in conjunction with multiple threads. The article over at InfoQ named <a href="http://www.infoq.com/news/2007/09/confusing_uow_with_threads">Confusing unit-of-work with threads</a> gives a good overview on the caveats lurking there.</p>
<p>Now, how do we use this Unit Of Work?</p>
<p><strong>Usage in ASP.NET applications</strong></p>
<p>There is a great deal of concensus on how to apply the unit of work pattern in web applications in general and in ASP.NET in particular.</p>
<p>In general, in web applications the Unit Of Work per Request implementation is used. You can find a sample implementation  in the article <a href="http://www.mindscape.co.nz/blog/index.php/2008/05/12/using-the-unit-of-work-per-request-pattern-in-aspnet-mvc/"> Using the unit of work-per-request pattern in ASP.NET MVC</a> and using NHibernate in <a href="http://www.codeproject.com/KB/architecture/NHibernateBestPractices.aspx">NHibernate Best Practices with ASP.NET</a><br />
An alternative is the Unit Of Work per Conversation. The <a href="http://marcus-schulte.ch/transactions.html">Transactions and Units of Work in Web-Applications</a> article gives a good general introduction and the post <a href="http://stackoverflow.com/questions/477267/what-are-the-benefits-of-session-per-conversation/477639">What are the benefits of session-per-conversation?</a> compares the two approaches.</p>
<p><strong>Usage in Windows Foms applications</strong></p>
<p>Windows  Forms applications are a completely different beast. In a web application there is a natural boundary of a request. There is however no  such thing in a winforms application. So finding guidance is difficult. The abone mentioned post <a href="http://marcus-schulte.ch/transactions.html">Transactions and Units of Work in Web-Applications</a> is a good start.</p>
<p><strong>Conclusion</strong></p>
<p>The Unit Of Work pattern is a basic pattern to streamline data access in applications. It provides a means to keep track of changes to your business objects and apply the changes as a single unit of work to your database,</p>
<p>I hope you found the links illumminating and if you have any yourself, please leave a comment.</p>
<p><strong>Links</strong><br />
Definition:<br />
<a href="http://martinfowler.com/eaaCatalog/unitOfWork.html">P of EAA: Unit of Work</a><br />
<a href="http://takacsot.freeblog.hu/Files/martinfowler/unitOfWork.html">IS Architecture Pattern: Unit of Work</a></p>
<p>Implementation:<br />
<a href="http://www.codeinsanity.com/2008/09/unit-of-work-pattern.html">Code Insanity: The Unit of Work Pattern</a><br />
<a href="http://www.codeinsanity.com/2008/10/implementing-persistence-ignorant-unit.html">Code Insanity: Implementing a persistence ignorant Unit of Work framework</a><br />
<a href="http://www.infoq.com/news/2007/09/confusing_uow_with_threads">InfoQ: Confusing unit-of-work with threads</a></p>
<p>General usage:<br />
<a href="http://marcus-schulte.ch/transactions.html">Transactions and Units of Work in Web-Applications</a></p>
<p>In ASP.NET:<br />
<a href="http://www.mindscape.co.nz/blog/index.php/2008/05/12/using-the-unit-of-work-per-request-pattern-in-aspnet-mvc/">Using the unit of work-per-request pattern in ASP.NET MVC</a><br />
<a href="http://www.codeproject.com/KB/architecture/NHibernateBestPractices.aspx">NHibernate Best Practices with ASP.NET, 1.2nd Ed.</a><br />
<a href="http://stackoverflow.com/questions/229621/appling-unit-of-work-pattern">Appling Unit Of Work pattern</a><br />
<a href="http://iridescence.no/post/ASPNET-MVC-DataContext-and-The-Unit-of-Work-Pattern.aspx">ASP.NET MVC, DataContext and The Unit of Work Pattern</a></p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sdesmedt.wordpress.com/648/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sdesmedt.wordpress.com/648/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sdesmedt.wordpress.com/648/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sdesmedt.wordpress.com/648/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sdesmedt.wordpress.com/648/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sdesmedt.wordpress.com/648/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sdesmedt.wordpress.com/648/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sdesmedt.wordpress.com/648/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sdesmedt.wordpress.com/648/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sdesmedt.wordpress.com/648/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sdesmedt.wordpress.com&blog=158868&post=648&subd=sdesmedt&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://sdesmedt.wordpress.com/2009/02/18/unit-of-work-pattern/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/97a1a6d85466d4f9c0c7fe6baa93478b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sdesmedt</media:title>
		</media:content>
	</item>
	</channel>
</rss>