<?xml version="1.0" encoding="utf-8"?><rss version="2.0"><channel><title>IanG on Tap</title><link>http://www.interact-sw.co.uk/iangblog/</link><description>Ian Griffiths in Weblog Form</description><copyright>(C) 2004 I D Griffiths</copyright><lastBuildDate>Wed, 30 Jul 2008 19:28:44 GMT</lastBuildDate><generator>Interact Blogger</generator><managingEditor>ian@interact-sw.co.uk</managingEditor><webMaster>ian@interact-sw.co.uk</webMaster><item><title>LINQ Aggregation and Bounding Boxes</title><guid isPermaLink="true">http://www.interact-sw.co.uk/iangblog/2008/07/30/linq-box-aggregation</guid><link>http://www.interact-sw.co.uk/iangblog/2008/07/30/linq-box-aggregation</link><pubDate>Wed, 30 Jul 2008 18:56:27 GMT</pubDate><description>&lt;p&gt;I recently worked on a project that included code to calculate the bounding box of a collection of rectangles. The code did more or less what you might expect – it iterated over the collection, and any time a new rectangle wasn’t contained by the current bounds, it enlarged the bounds to fit.&lt;/p&gt;
&lt;p&gt;There was nothing wrong with this, but I knew of a cute trick that could do the job with a fraction of the code. I wasn’t being paid to replace working code with cute tricks, so I left it as it was – when it comes to production code I’m not a fan of the “If it ain’t broke, let me take a crack at it” school of coding. So I thought I’d illustrate the idea here instead.&lt;/p&gt;
&lt;p&gt;Here’s a one-line implementation of the same logic, using the &lt;code&gt;System.Windows.Rect&lt;/code&gt; type in WPF. (Note that this is a very simple value type, not a full UI element. It’s just 4 numbers.)&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;public&lt;/span&gt; &lt;span style="color:blue"&gt;static&lt;/span&gt; &lt;span style="color:dimgray"&gt;Rect&lt;/span&gt; GetBounds(&lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:dimgray"&gt;Rect&lt;/span&gt;&amp;gt; rects)
{
    &lt;span style="color:blue"&gt;return&lt;/span&gt; rects.Aggregate((currBounds, nextRect) =&amp;gt; &lt;span style="color:dimgray"&gt;Rect&lt;/span&gt;.Union(currBounds, nextRect));
}
&lt;/pre&gt;
&lt;p&gt;That’s pleasingly succinct, although possibly a little obscure if you’re not accustomed to this style of coding. Actually we can go one more notch on the obscure-and-succinct scale. This comes to the same thing:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;public&lt;/span&gt; &lt;span style="color:blue"&gt;static&lt;/span&gt; &lt;span style="color:dimgray"&gt;Rect&lt;/span&gt; GetBounds(&lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:dimgray"&gt;Rect&lt;/span&gt;&amp;gt; rects)
{
    &lt;span style="color:blue"&gt;return&lt;/span&gt; rects.Aggregate(&lt;span style="color:dimgray"&gt;Rect&lt;/span&gt;.Union);
}
&lt;/pre&gt;
&lt;p&gt;LINQ’s standard Aggregate method implements a mechanism often known as &lt;a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)"&gt;fold&lt;/a&gt; in functional programming languages. It’s a pretty simple idea: apply some sort of cumulative operation across all items in a list to build up some sort running total. In this example, LINQ’s uses the first item in the list as the starting point. (Alternatively, you can provide an explicit start value.) It passes that in to the function supplied, along with the second item. The result becomes the new running total, which is fed again into the function supplied, this time along with the third item...and so on. Each time round the aggregating function we provide gets the running total as its first argument, and the next item in the list as its second.&lt;/p&gt;
&lt;p&gt;It’s easier to show what it does than to describe it. Here’s what that code would do if applied to an array containing five Rects:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:dimgray"&gt;Rect&lt;/span&gt;.Union(&lt;span style="color:dimgray"&gt;Rect&lt;/span&gt;.Union(&lt;span style="color:dimgray"&gt;Rect&lt;/span&gt;.Union(&lt;span style="color:dimgray"&gt;Rect&lt;/span&gt;.Union(rs[0], rs[1]), rs[2]), rs[3]), rs[4])
&lt;/pre&gt;
&lt;p&gt;Or if you prefer sequential imperative code, you might like to picture it as:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:dimgray"&gt;Rect&lt;/span&gt; currBounds = rs[0];
currBounds = &lt;span style="color:dimgray"&gt;Rect&lt;/span&gt;.Union(currBounds, rs[1]);
currBounds = &lt;span style="color:dimgray"&gt;Rect&lt;/span&gt;.Union(currBounds, rs[2]);
currBounds = &lt;span style="color:dimgray"&gt;Rect&lt;/span&gt;.Union(currBounds, rs[3]);
currBounds = &lt;span style="color:dimgray"&gt;Rect&lt;/span&gt;.Union(currBounds, rs[4]);
&lt;/pre&gt;
&lt;p&gt;As you can see, it’s not particularly magical. It’s nothing you couldn’t implement with a straightforward loop. (Or with tedious duplication, as here.) But it’s an idea that crops up often enough that it’s rather handy to have as general purpose function – you get to specify what you’d like to use as the cumulative operation, and LINQ does the rest for you.&lt;/p&gt;
&lt;p&gt;Aggregate can be used to implement some common operations. For example, you can use it to sum together all the numbers in a list:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;public&lt;/span&gt; &lt;span style="color:blue"&gt;static&lt;/span&gt; &lt;span style="color:blue"&gt;int&lt;/span&gt; Sum(&lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:blue"&gt;int&lt;/span&gt;&amp;gt; numbers)
{
    &lt;span style="color:blue"&gt;return&lt;/span&gt; numbers.Aggregate((currTotal, nextInt) =&amp;gt; currTotal + nextInt);
}
&lt;/pre&gt;
&lt;p&gt;Or you could use it to find the highest number in a list:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;public&lt;/span&gt; &lt;span style="color:blue"&gt;static&lt;/span&gt; &lt;span style="color:blue"&gt;int&lt;/span&gt; Max(&lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:blue"&gt;int&lt;/span&gt;&amp;gt; numbers)
{
    &lt;span style="color:blue"&gt;return&lt;/span&gt; numbers.Aggregate((highest, nextInt) =&amp;gt; &lt;span style="color:dimgray"&gt;Math&lt;/span&gt;.Max(highest, nextInt));
}
&lt;/pre&gt;
&lt;p&gt;or again, since this just forwards the arguments directly to a function, we can skip the lambda and use the more terse form:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;public&lt;/span&gt; &lt;span style="color:blue"&gt;static&lt;/span&gt; &lt;span style="color:blue"&gt;int&lt;/span&gt; Max(&lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:blue"&gt;int&lt;/span&gt;&amp;gt; numbers)
{
    &lt;span style="color:blue"&gt;return&lt;/span&gt; numbers.Aggregate(&lt;span style="color:dimgray"&gt;Math&lt;/span&gt;.Max);
}
&lt;/pre&gt;
&lt;p&gt;Of course, you don’t need to write these two examples, because LINQ already supplies Sum and Max extension methods for you. But conceptually at least, they’re just a handy shortcut to a specialized form of aggregation.&lt;/p&gt;
&lt;p&gt;Getting the total bounding box of all of the rectangles in a list is not so different from finding the highest number – it’s just a slightly different kind of maximum.&lt;/p&gt;
&lt;p&gt;Not a particularly astounding idea, admittedly. I just thought it was a neat trick, and wanted to share it.&lt;/p&gt;</description></item><item><title>Visual State in Silverlight Control Templates</title><guid isPermaLink="true">http://www.interact-sw.co.uk/iangblog/2008/06/10/visual-state</guid><link>http://www.interact-sw.co.uk/iangblog/2008/06/10/visual-state</link><pubDate>Tue, 10 Jun 2008 20:38:46 GMT</pubDate><description>&lt;p&gt;&lt;a href="http://silverlight.net/GetStarted/"&gt;Silverlight 2&lt;/a&gt; introduces a mechanism for customizing the dynamic aspects of a control’s appearance. This new model appeared for the first time in the &lt;a href="http://weblogs.asp.net/scottgu/archive/2008/06/06/silverlight-2-beta2-released.aspx"&gt;recent beta 2 release&lt;/a&gt;, so I thought I’d take a crack at explaining it.&lt;/p&gt;
&lt;h3&gt;The Role of Visual States&lt;/h3&gt;
&lt;p&gt;In both Silverlight and WPF, a control’s appearance can be customized by providing a ‘template’. Templates are typically written in Xaml, and all the usual visual elements are available. But it’s usually not enough just to define the static structure of a control’s visuals.&lt;/p&gt;
&lt;p&gt;Most controls change their appearance when the user interacts with them. We expect elements to signal their ability to respond to input with subtle visual shifts when the mouse moves over them, for example. And this is where Silverlight’s ‘visual states’ come in. You can associate animations with visual state changes.&lt;/p&gt;
&lt;p&gt;(If you know WPF you’ll be familiar with triggers, which enable exactly this sort of connection between interaction and visuals. In an omission some WPF veterans find surprising, Silverlight doesn’t support triggers. Visual states are what we use instead.)&lt;/p&gt;
&lt;h3&gt;States and State Groups&lt;/h3&gt;
&lt;p&gt;To work with Silverlight’s visual state system, we must get to grips with &lt;i&gt;states&lt;/i&gt; and &lt;i&gt;state group&lt;/i&gt;&lt;i&gt;s&lt;/i&gt;.&lt;/p&gt;
&lt;p&gt;A control might have many facets, each with its own visual representation. For example, a checkbox may be checked, or unchecked. And it may also be focused or unfocused. The checked/unchecked state is wholly independent of the focused/unfocused state: the keyboard focus can move into and out of the control without changing the checked state. But not all states can be freely combined – obviously a checkbox cannot be both checked and unchecked (although it might be neither – there’s a third, ‘indeterminate’ state, but that’s mutually exclusive with both checked and unchecked).&lt;/p&gt;
&lt;p&gt;To clarify how states may combine, states are partitioned into state groups. For example, &lt;code&gt;CheckBox&lt;/code&gt; defines three state groups:&lt;/p&gt;
&lt;table cellspacing="0" class="blgTb"&gt;
  &lt;tr&gt;
    &lt;th class="blgTbFstCol"&gt;Group Name&lt;/th&gt;
    &lt;th&gt;States&lt;/th&gt;
  &lt;/tr&gt;
&lt;tr&gt;
    &lt;td&gt;CommonStates&lt;/td&gt;
    &lt;td&gt;Normal, MouseOver, Pressed, Disabled&lt;/td&gt;
  &lt;/tr&gt;
&lt;tr&gt;
    &lt;td&gt;CheckStates&lt;/td&gt;
    &lt;td&gt;Checked, Unchecked, Indeterminate&lt;/td&gt;
  &lt;/tr&gt;
&lt;tr&gt;
    &lt;td&gt;FocusStates&lt;/td&gt;
    &lt;td&gt;Focused, ContentFocused, Unfocused&lt;/td&gt;
  &lt;/tr&gt;
&lt;/table&gt;
&lt;p&gt;So if we ask “What is a &lt;code&gt;CheckBox&lt;/code&gt;’s state?” the answer comes in three parts: a state from the &lt;code&gt;CommonStates&lt;/code&gt; state group, one from &lt;code&gt;CheckStates&lt;/code&gt;, and one from &lt;code&gt;FocusStates&lt;/code&gt;. A control effectively maintains multiple state machines, one for each state group. Here are some examples:&lt;/p&gt;
&lt;p&gt;&lt;img src="http://www.interact-sw.co.uk/images/SilverlightCheckStates.png" alt="http://www.interact-sw.co.uk/images/SilverlightCheckStates.png"&gt;&lt;/p&gt;
&lt;p&gt;For the &lt;code&gt;CheckStates&lt;/code&gt; state group, all three checkboxes here are in the &lt;code&gt;Checked&lt;/code&gt; state. With respect to the &lt;code&gt;FocusStates&lt;/code&gt; state group, the first checkbox is in the &lt;code&gt;Focused&lt;/code&gt; state, while the second and third are in the &lt;code&gt;Unfocused&lt;/code&gt; state. Finally, as far as the &lt;code&gt;CommonStates&lt;/code&gt; state group is concerned, the first and third checkboxes are in the &lt;code&gt;Normal&lt;/code&gt; state, while the second is in the &lt;code&gt;MouseOver&lt;/code&gt; state. (The mouse cursor isn’t shown here, but you can see that the control has changed appearance.)&lt;/p&gt;
&lt;p&gt;A control will advertise the states it offers and the group to which each state belongs with the &lt;code&gt;TemplateVisualState&lt;/code&gt; attribute, as you can see here:&lt;/p&gt;
&lt;pre&gt;[&lt;span style="color:dimgray"&gt;TemplateVisualState&lt;/span&gt;(Name = &lt;span style="color:brown"&gt;"ContentFocused"&lt;/span&gt;, GroupName = &lt;span style="color:brown"&gt;"FocusStates"&lt;/span&gt;)]
[&lt;span style="color:dimgray"&gt;TemplateVisualState&lt;/span&gt;(Name = &lt;span style="color:brown"&gt;"MouseOver"&lt;/span&gt;, GroupName = &lt;span style="color:brown"&gt;"CommonStates"&lt;/span&gt;)]
[&lt;span style="color:dimgray"&gt;TemplateVisualState&lt;/span&gt;(Name = &lt;span style="color:brown"&gt;"Focused"&lt;/span&gt;, GroupName = &lt;span style="color:brown"&gt;"FocusStates"&lt;/span&gt;)]
[&lt;span style="color:dimgray"&gt;TemplateVisualState&lt;/span&gt;(Name = &lt;span style="color:brown"&gt;"Checked"&lt;/span&gt;, GroupName = &lt;span style="color:brown"&gt;"CheckStates"&lt;/span&gt;)]
[&lt;span style="color:dimgray"&gt;TemplateVisualState&lt;/span&gt;(Name = &lt;span style="color:brown"&gt;"Unchecked"&lt;/span&gt;, GroupName = &lt;span style="color:brown"&gt;"CheckStates"&lt;/span&gt;)]
[&lt;span style="color:dimgray"&gt;TemplateVisualState&lt;/span&gt;(Name = &lt;span style="color:brown"&gt;"Indeterminate"&lt;/span&gt;, GroupName = &lt;span style="color:brown"&gt;"CheckStates"&lt;/span&gt;)]
[&lt;span style="color:dimgray"&gt;TemplateVisualState&lt;/span&gt;(Name = &lt;span style="color:brown"&gt;"Pressed"&lt;/span&gt;, GroupName = &lt;span style="color:brown"&gt;"CommonStates"&lt;/span&gt;)]
[&lt;span style="color:dimgray"&gt;TemplateVisualState&lt;/span&gt;(Name = &lt;span style="color:brown"&gt;"Disabled"&lt;/span&gt;, GroupName = &lt;span style="color:brown"&gt;"CommonStates"&lt;/span&gt;)]
[&lt;span style="color:dimgray"&gt;TemplateVisualState&lt;/span&gt;(Name = &lt;span style="color:brown"&gt;"Unfocused"&lt;/span&gt;, GroupName = &lt;span style="color:brown"&gt;"FocusStates"&lt;/span&gt;)]
[&lt;span style="color:dimgray"&gt;TemplateVisualState&lt;/span&gt;(Name = &lt;span style="color:brown"&gt;"Normal"&lt;/span&gt;, GroupName = &lt;span style="color:brown"&gt;"CommonStates"&lt;/span&gt;)]
&lt;span style="color:blue"&gt;public&lt;/span&gt; &lt;span style="color:blue"&gt;class&lt;/span&gt; &lt;span style="color:dimgray"&gt;CheckBox&lt;/span&gt; : &lt;span style="color:dimgray"&gt;ToggleButton &lt;/span&gt;...
&lt;/pre&gt;
&lt;p&gt;We now know that a control will maintain a simple state machine for each state group. So what? To do anything useful with this, we must use the &lt;code&gt;VisualStateManager&lt;/code&gt; class.&lt;/p&gt;
&lt;h3&gt;VisualStateManager&lt;/h3&gt;
&lt;p&gt;The &lt;code&gt;VisualStateManager&lt;/code&gt; class lets us connect animations to state changes. It defines an attached property we can use to establish these connections in Xaml.&lt;/p&gt;
&lt;p&gt;So that we can see this in action, let’s start with a simple template for a &lt;code&gt;CheckBox&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;CheckBox&lt;/span&gt;&lt;span style="color:red"&gt; Content&lt;/span&gt;&lt;span style="color:blue"&gt;="Check!"&lt;/span&gt;&lt;span style="color:red"&gt; IsChecked&lt;/span&gt;&lt;span style="color:blue"&gt;="True"&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;  &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;CheckBox.Template&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;    &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;ControlTemplate&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;      &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;Grid&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;        &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;Grid.ColumnDefinitions&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;          &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;ColumnDefinition&lt;/span&gt;&lt;span style="color:red"&gt; Width&lt;/span&gt;&lt;span style="color:blue"&gt;="19" /&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;          &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;ColumnDefinition&lt;/span&gt;&lt;span style="color:blue"&gt; /&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;        &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color:brown"&gt;Grid.ColumnDefinitions&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;

&lt;span style="color:brown"&gt;        &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;vsm&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:brown"&gt;VisualStateManager.VisualStateGroups&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;        &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color:brown"&gt;vsm&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:brown"&gt;VisualStateManager.VisualStateGroups&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;

&lt;span style="color:brown"&gt;        &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;Rectangle&lt;/span&gt;&lt;span style="color:red"&gt; x&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:red"&gt;Name&lt;/span&gt;&lt;span style="color:blue"&gt;="tickBox"&lt;/span&gt;
         &lt;span style="color:red"&gt; Stroke&lt;/span&gt;&lt;span style="color:blue"&gt;="Blue"&lt;/span&gt;&lt;span style="color:red"&gt; Width&lt;/span&gt;&lt;span style="color:blue"&gt;="12"&lt;/span&gt;&lt;span style="color:red"&gt; Height&lt;/span&gt;&lt;span style="color:blue"&gt;="12"&lt;/span&gt;&lt;span style="color:red"&gt; HorizontalAlignment&lt;/span&gt;&lt;span style="color:blue"&gt;="Left"&lt;/span&gt;
         &lt;span style="color:red"&gt; RadiusX&lt;/span&gt;&lt;span style="color:blue"&gt;="2"&lt;/span&gt;&lt;span style="color:red"&gt; RadiusY&lt;/span&gt;&lt;span style="color:blue"&gt;="2"&lt;/span&gt;&lt;span style="color:red"&gt; Fill&lt;/span&gt;&lt;span style="color:blue"&gt;="Aqua" /&amp;gt;&lt;/span&gt;

&lt;span style="color:brown"&gt;        &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;Path&lt;/span&gt;&lt;span style="color:red"&gt; x&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:red"&gt;Name&lt;/span&gt;&lt;span style="color:blue"&gt;="tick"&lt;/span&gt;&lt;span style="color:red"&gt; Opacity&lt;/span&gt;&lt;span style="color:blue"&gt;="0"&lt;/span&gt;
             &lt;span style="color:red"&gt; Width&lt;/span&gt;&lt;span style="color:blue"&gt;="12"&lt;/span&gt;&lt;span style="color:red"&gt; Height&lt;/span&gt;&lt;span style="color:blue"&gt;="12"&lt;/span&gt;&lt;span style="color:red"&gt; HorizontalAlignment&lt;/span&gt;&lt;span style="color:blue"&gt;="Left"&lt;/span&gt;
             &lt;span style="color:red"&gt; Stroke&lt;/span&gt;&lt;span style="color:blue"&gt;="Black"&lt;/span&gt;&lt;span style="color:red"&gt; StrokeThickness&lt;/span&gt;&lt;span style="color:blue"&gt;="2"&lt;/span&gt;
             &lt;span style="color:red"&gt; Data&lt;/span&gt;&lt;span style="color:blue"&gt;="M3,6 L5,9 9,2" /&amp;gt;&lt;/span&gt;

&lt;span style="color:brown"&gt;        &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;ContentPresenter&lt;/span&gt;&lt;span style="color:red"&gt; Grid.Column&lt;/span&gt;&lt;span style="color:blue"&gt;="1" /&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;      &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color:brown"&gt;Grid&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;    &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color:brown"&gt;ControlTemplate&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;  &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color:brown"&gt;CheckBox.Template&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;
&lt;span style="color:blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color:brown"&gt;CheckBox&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;
&lt;/pre&gt;
&lt;p&gt;This defines some pretty basic visuals – just a simple box and tick, plus a placeholder. It looks like this:&lt;/p&gt;
&lt;p&gt;&lt;img src="http://www.interact-sw.co.uk/images/SilverlightStatesCustom1.png" alt="http://www.interact-sw.co.uk/images/SilverlightStatesCustom1.png"&gt;&lt;/p&gt;
&lt;p&gt;Note that although I’ve got a &lt;code&gt;Path&lt;/code&gt; element in the shape of a tick, it’s currently invisible. Later I will supply a couple of animations to make the tick visible and invisible.&lt;/p&gt;
&lt;p&gt;Notice that the example above already contains an empty &lt;code&gt;&amp;lt;&lt;/code&gt;&lt;code&gt;vsm&lt;/code&gt;&lt;code&gt;:VisualStateManager.VisualStateGroups&lt;/code&gt;&lt;code&gt;&amp;gt;&lt;/code&gt; element – it’s just after the grid’s column definitions. I’ve been working with Xaml for half a decade now, but for anyone who hasn’t had that pleasure, I suppose it might not be totally obvious that this element sets a property on the containing &lt;code&gt;Grid&lt;/code&gt;! In general, Xaml elements of the form &lt;code&gt;&amp;lt;&lt;/code&gt;&lt;code&gt;Xxx.Yyy&lt;/code&gt;&lt;code&gt;&amp;gt;&lt;/code&gt; denote a property. The part after the ‘.’ is the property name, so that tells us that this is the &lt;code&gt;VisualStateGroups&lt;/code&gt; property. And the part before the ‘.’ is the name of the class that defines the property – so here we can see this property is defined by the &lt;code&gt;VisualStateManager&lt;/code&gt; class. Again, if you’re not familiar with Xaml, it may seem a bit funky that I can set property defined by &lt;code&gt;VisualStateManager&lt;/code&gt; on &lt;code&gt;Grid&lt;/code&gt;, a completely unrelated class. This is an example of a Xaml feature called &lt;i&gt;attached properties&lt;/i&gt;– they’re a way of bolting new properties onto existing types.&lt;/p&gt;
&lt;p&gt;For some reason the &lt;code&gt;VisualStateManager&lt;/code&gt; class isn’t in the Silverlight Xaml namespace, so we’ve had to qualify it with a namespace prefix. (I’ve chosen “vsm:” in this example, short for &lt;code&gt;VisualStateManager&lt;/code&gt;.) For this to work, I need to have defined that prefix somewhere in my Xaml. It’s not shown in the above snippet, but I put it at the root element, alongside the other namespace declarations:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:red"&gt;xmlns&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:red"&gt;vsm&lt;/span&gt;&lt;span style="color:blue"&gt;="clr-namespace:System.Windows;assembly=System.Windows"&lt;/span&gt;
&lt;/pre&gt;
&lt;p&gt;Normally you’d let Blend do all this for you. The June preview of Expression Blend 2.5 provides new features for working with the &lt;code&gt;VisualStateManager&lt;/code&gt;. But my goal here is to explain the underlying mechanisms, so I’ll steer clear of Blend for now.&lt;/p&gt;
&lt;p&gt;&lt;b&gt;&lt;i&gt;Note&lt;/i&gt;&lt;/b&gt;&lt;i&gt;: in the Silverlight 2 beta 2 preview bits, the Visual Studio &lt;/i&gt;&lt;i&gt;Xaml&lt;/i&gt;&lt;i&gt; editor &lt;/i&gt;&lt;i&gt;reports &lt;/i&gt;&lt;i&gt;an error&lt;/i&gt;&lt;i&gt; on the line with this property. It says&lt;/i&gt;&lt;i&gt;: “The attachable property ‘&lt;/i&gt;&lt;i&gt;VisualStateGroups&lt;/i&gt;&lt;i&gt;’ was not found in type ‘&lt;/i&gt;&lt;i&gt;VisualStateManager&lt;/i&gt;&lt;i&gt;’.” &lt;/i&gt;&lt;i&gt;But it’s lying – the attachable property is present, and although you get what looks like an error in Visual Studio.&lt;/i&gt;&lt;i&gt; But you’ll find the project will happily build and run despite this &lt;/i&gt;&lt;i&gt;‘error’, and if you close the &lt;/i&gt;&lt;i&gt;Xaml&lt;/i&gt;&lt;i&gt; editor, the error goes away. It’s not really an error. That’s beta software for you.&lt;/i&gt;&lt;/p&gt;
&lt;p&gt;So what do we put inside this property? We can provide an animation to run for each state. On top of that, we can optionally get fancy, and provide animations that handle the transition between a specific pair of states. Let’s start with the simpler case.&lt;/p&gt;
&lt;h3&gt;Per-State Animations&lt;/h3&gt;
&lt;p&gt;The simplest way to use the visual state manager is to define an animation to run when a particular state is entered. The following example is about as simple as it gets:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;vsm&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:brown"&gt;VisualStateManager.VisualStateGroups&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;  &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;vsm&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:brown"&gt;VisualStateGroup&lt;/span&gt;&lt;span style="color:red"&gt; x&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:red"&gt;Name&lt;/span&gt;&lt;span style="color:blue"&gt;="CommonStates"&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;    &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;vsm&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:brown"&gt;VisualState&lt;/span&gt;&lt;span style="color:red"&gt; x&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:red"&gt;Name&lt;/span&gt;&lt;span style="color:blue"&gt;="MouseOver"&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;      &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;Storyboard&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;        &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;ColorAnimation&lt;/span&gt;&lt;span style="color:red"&gt; Storyboard.TargetName&lt;/span&gt;&lt;span style="color:blue"&gt;="tickBox"&lt;/span&gt;
           &lt;span style="color:red"&gt; Storyboard.TargetProperty&lt;/span&gt;&lt;span style="color:blue"&gt;="(Rectangle.Fill).&lt;/span&gt;
&lt;span style="color:blue"&gt;                                (SolidColorBrush.Color)"&lt;/span&gt;
            &lt;span style="color:red"&gt;To&lt;/span&gt;&lt;span style="color:blue"&gt;="PaleGreen"&lt;/span&gt;&lt;span style="color:red"&gt; Duration&lt;/span&gt;&lt;span style="color:blue"&gt;="0:0:0.5" /&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;      &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color:brown"&gt;Storyboard&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;    &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color:brown"&gt;vsm&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:brown"&gt;VisualState&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;  &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color:brown"&gt;vsm&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:brown"&gt;VisualStateGroup&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;
&lt;span style="color:blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color:brown"&gt;vsm&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:brown"&gt;VisualStateManager.VisualStateGroups&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;
&lt;/pre&gt;
&lt;p&gt;Notice that I am required to say first of all which &lt;i&gt;state group&lt;/i&gt; I’m interested in, with a &lt;code&gt;VisualStateGroup&lt;/code&gt; element. In this case, I’m looking at the &lt;code&gt;CommonStates&lt;/code&gt; group. And inside the group, I provide a &lt;code&gt;VisualState&lt;/code&gt; element for each state I wish to animate. To keep things simple, I’ve just handled one state here: &lt;code&gt;MouseOver&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;With this markup in place, when the &lt;code&gt;CommonStates&lt;/code&gt; state group enters the &lt;code&gt;MouseOver&lt;/code&gt; state (i.e. when the user moves the mouse over the control), the &lt;code&gt;Storyboard&lt;/code&gt; I’ve supplied here will run. This particular animation changes the checkbox’s fill to pale green.&lt;/p&gt;
&lt;p&gt;Since I’ve only handled one state, the checkbox will get stuck in that state – I’ve not yet provided any animations to put it back how it was. And I’m also missing some other states, so to complete the job, I should add the following inside that &lt;code&gt;VisualStateGroup&lt;/code&gt; after the first &lt;code&gt;VisualState&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;vsm&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:brown"&gt;VisualState&lt;/span&gt;&lt;span style="color:red"&gt; x&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:red"&gt;Name&lt;/span&gt;&lt;span style="color:blue"&gt;="Pressed"&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;  &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;Storyboard&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;    &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;ColorAnimation&lt;/span&gt;&lt;span style="color:red"&gt; Storyboard.TargetName&lt;/span&gt;&lt;span style="color:blue"&gt;="tickBox"&lt;/span&gt;
                   &lt;span style="color:red"&gt; Storyboard.TargetProperty&lt;/span&gt;&lt;span style="color:blue"&gt;="(Rectangle.Fill).&lt;/span&gt;
&lt;span style="color:blue"&gt;                    (SolidColorBrush.Color)"&lt;/span&gt;
                   &lt;span style="color:red"&gt; To&lt;/span&gt;&lt;span style="color:blue"&gt;="Navy"&lt;/span&gt;&lt;span style="color:red"&gt; Duration&lt;/span&gt;&lt;span style="color:blue"&gt;="0:0:0.5" /&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;  &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color:brown"&gt;Storyboard&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;
&lt;span style="color:blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color:brown"&gt;vsm&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:brown"&gt;VisualState&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;
&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;vsm&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:brown"&gt;VisualState&lt;/span&gt;&lt;span style="color:red"&gt; x&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:red"&gt;Name&lt;/span&gt;&lt;span style="color:blue"&gt;="Disabled"&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;  &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;Storyboard&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;    &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;ColorAnimation&lt;/span&gt;&lt;span style="color:red"&gt; Storyboard.TargetName&lt;/span&gt;&lt;span style="color:blue"&gt;="tickBox"&lt;/span&gt;
                   &lt;span style="color:red"&gt; Storyboard.TargetProperty&lt;/span&gt;&lt;span style="color:blue"&gt;="(Rectangle.Fill).&lt;/span&gt;
&lt;span style="color:blue"&gt;                    (SolidColorBrush.Color)"&lt;/span&gt;
                   &lt;span style="color:red"&gt; To&lt;/span&gt;&lt;span style="color:blue"&gt;="Gray"&lt;/span&gt;&lt;span style="color:red"&gt; Duration&lt;/span&gt;&lt;span style="color:blue"&gt;="0:0:0.5" /&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;  &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color:brown"&gt;Storyboard&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;
&lt;span style="color:blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color:brown"&gt;vsm&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:brown"&gt;VisualState&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;
&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;vsm&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:brown"&gt;VisualState&lt;/span&gt;&lt;span style="color:red"&gt; x&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:red"&gt;Name&lt;/span&gt;&lt;span style="color:blue"&gt;="Normal"&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;  &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;Storyboard&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;    &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;ColorAnimation&lt;/span&gt;&lt;span style="color:red"&gt; Storyboard.TargetName&lt;/span&gt;&lt;span style="color:blue"&gt;="tickBox"&lt;/span&gt;
                   &lt;span style="color:red"&gt; Storyboard.TargetProperty&lt;/span&gt;&lt;span style="color:blue"&gt;="(Rectangle.Fill).&lt;/span&gt;
&lt;span style="color:blue"&gt;                    (SolidColorBrush.Color)"&lt;/span&gt;&lt;span style="color:red"&gt; Duration&lt;/span&gt;&lt;span style="color:blue"&gt;="0:0:0.5" /&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;  &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color:brown"&gt;Storyboard&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;
&lt;span style="color:blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color:brown"&gt;vsm&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:brown"&gt;VisualState&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;
&lt;/pre&gt;
&lt;p&gt;Note that the last of these doesn’t specify the &lt;code&gt;To&lt;/code&gt; attribute for the animation. As is usual for animations in Silverlight and WPF, this means ‘animate back to the base value’, which is exactly what you’d hope for when returning to the &lt;code&gt;Normal&lt;/code&gt; state.&lt;/p&gt;
&lt;p&gt;I’m going to use a similar but cruder trick to handle the checkbox state. The following goes after the first &lt;code&gt;VisualStateGroup&lt;/code&gt; element:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;vsm&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:brown"&gt;VisualStateGroup&lt;/span&gt;&lt;span style="color:red"&gt; x&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:red"&gt;Name&lt;/span&gt;&lt;span style="color:blue"&gt;="CheckStates"&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;  &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;vsm&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:brown"&gt;VisualState&lt;/span&gt;&lt;span style="color:red"&gt; x&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:red"&gt;Name&lt;/span&gt;&lt;span style="color:blue"&gt;="Checked"&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;    &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;Storyboard&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;      &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;DoubleAnimation&lt;/span&gt;&lt;span style="color:red"&gt; Storyboard.TargetName&lt;/span&gt;&lt;span style="color:blue"&gt;="tick"&lt;/span&gt; 
                      &lt;span style="color:red"&gt; Storyboard.TargetProperty&lt;/span&gt;&lt;span style="color:blue"&gt;="Opacity"&lt;/span&gt;
                      &lt;span style="color:red"&gt; To&lt;/span&gt;&lt;span style="color:blue"&gt;="1"&lt;/span&gt;&lt;span style="color:red"&gt; Duration&lt;/span&gt;&lt;span style="color:blue"&gt;="0" /&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;    &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color:brown"&gt;Storyboard&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;  &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color:brown"&gt;vsm&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:brown"&gt;VisualState&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;  &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;vsm&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:brown"&gt;VisualState&lt;/span&gt;&lt;span style="color:red"&gt; x&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:red"&gt;Name&lt;/span&gt;&lt;span style="color:blue"&gt;="Unchecked" /&amp;gt;&lt;/span&gt;
&lt;span style="color:blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color:brown"&gt;vsm&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:brown"&gt;VisualStateGroup&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;
&lt;/pre&gt;
&lt;p&gt;As before, this declares that I want to handle state changes for a particular state group – the &lt;code&gt;CheckStates&lt;/code&gt; group this time. And I’ve provided &lt;code&gt;VisualState&lt;/code&gt; elements to tell Silverlight what to do when entering either the &lt;code&gt;Checked&lt;/code&gt; or &lt;code&gt;Unchecked&lt;/code&gt; states.&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;Checked&lt;/code&gt; storyboard is slightly odd: it has a &lt;code&gt;Duration&lt;/code&gt; of 0. This is a case of trigger envy – in WPF I’d just write a simple trigger that says when &lt;code&gt;IsC&lt;/code&gt;&lt;code&gt;hecked&lt;/code&gt; is true, the ‘tick’ element should be visible. But Silverlight doesn’t have triggers, so instead I’ve had to use an animation that runs instantaneously to get the same effect.&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;Unchecked&lt;/code&gt; handling is even stranger: I’ve provided an empty &lt;code&gt;VisualState&lt;/code&gt; element. The significance of this is that I’m telling Silverlight that I care about this state, but that I have no new animations to run. And the important, non-obvious point is that when a new &lt;code&gt;VisualState&lt;/code&gt; element comes into play, Silverlight deactivates any animations that were previously in effect from other &lt;code&gt;VisualState&lt;/code&gt; elements for that state group.&lt;/p&gt;
&lt;p&gt;And even though my &lt;code&gt;Checked&lt;/code&gt; animation has a duration of 0, it remains active until we enter the &lt;code&gt;Unchecked&lt;/code&gt; state. Animations in Silverlight (and WPF) usually continue to have an effect even after they complete – if you animate something from red to green, it will remain green once the animation finishes. (You can change that if you like – this is controlled with the animation’s &lt;code&gt;FillBehavior&lt;/code&gt; property.) So in this case, the &lt;code&gt;Checked&lt;/code&gt; animation completes instantly, but remains active, holding the ‘tick’ element’s Opacity property at 1 until the animation is deactivated. That deactivation happens when we enter the &lt;code&gt;Unchecked&lt;/code&gt; state.&lt;/p&gt;
&lt;p&gt;So it’s quite common to see empty &lt;code&gt;VisualState&lt;/code&gt; elements. They’re usually present to deactivate any other animations for the state group.&lt;/p&gt;
&lt;p&gt;Note that the example so far is incomplete. I’ve not handled the &lt;code&gt;Indeterminate&lt;/code&gt; state in the &lt;code&gt;CheckStates&lt;/code&gt; group. And I’ve also not handled the &lt;code&gt;FocusStates&lt;/code&gt; state group at all. Nor do I plan to – I’m just trying to show the model here, and to fill in the gaps would mean more of the same.&lt;/p&gt;
&lt;p&gt;(If you want to see a fuller example, I’ve put focus state handling into the version available for download: &lt;a href="http://www.interact-sw.co.uk/downloads/SilverlightVisualStateDemo.zip"&gt;SilverlightVisualStateDemo.zip&lt;/a&gt;. If you want to run the application online, it’s up at &lt;a href="http://www.interact-sw.co.uk/slapps/visualstate/"&gt;http://www.interact-sw.co.uk/slapps/visualstate/&lt;/a&gt; Note that these versions also include the feature described in the next section.)&lt;/p&gt;
&lt;h3&gt;Transition Animations&lt;/h3&gt;
&lt;p&gt;Whereas the &lt;code&gt;VisualState&lt;/code&gt; element we’ve just seen defines the animation to use when entering a particular state, a transition animation is more specific: you can define the animation to run when transitioning between a particular pair of states.&lt;/p&gt;
&lt;p&gt;Note that transition animations do not replace the &lt;code&gt;VisualState&lt;/code&gt; animations. A transition animation runs &lt;i&gt;before&lt;/i&gt; the &lt;code&gt;VisualState&lt;/code&gt; animation. For example, suppose you’ve defined a transition animation for the transition from the &lt;code&gt;Pressed&lt;/code&gt; to &lt;code&gt;Normal&lt;/code&gt; states in the &lt;code&gt;CommonStates&lt;/code&gt; group. Silverlight will first run this transition animation, and once that has finished, it goes on to run the state animation.&lt;/p&gt;
&lt;p&gt;You might think that you could use transition animations as a replacement for state animations – why not provide only a transition, and leave out the final state animation? That turns out not to work: Silverlight requires you to specify the duration of your transition, and it will deactivate the transition animation at the end. And if you leave off the duration, the duration becomes 0 at which point the animation effectively never runs at all.&lt;/p&gt;
&lt;p&gt;This constraint ensures that no matter how a control entered a state, and no matter which transition animation ran as a result, it always ends up looking the same when it’s in that state, once all the animations have played out.&lt;/p&gt;
&lt;p&gt;To put it another way, Silverlight will always eventually run the animation for the target state, as specified in the relevant &lt;code&gt;VisualState&lt;/code&gt;, but before it runs that you get to insert something specific to the preceding state. This gives you just enough power to ensure that every possible state change looks coherent, while minimizing the scope for chaos.&lt;/p&gt;
&lt;p&gt;Here’s a simple and slightly contrived example:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;vsm&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:brown"&gt;VisualStateGroup&lt;/span&gt;&lt;span style="color:red"&gt; x&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:red"&gt;Name&lt;/span&gt;&lt;span style="color:blue"&gt;="CommonStates"&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;  &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;vsm&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:brown"&gt;VisualStateGroup.Transitions&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;    &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;vsm&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:brown"&gt;VisualTransition&lt;/span&gt;&lt;span style="color:red"&gt; From&lt;/span&gt;&lt;span style="color:blue"&gt;="Pressed"&lt;/span&gt;&lt;span style="color:red"&gt; To&lt;/span&gt;&lt;span style="color:blue"&gt;="Normal"&lt;/span&gt;&lt;span style="color:red"&gt; Duration&lt;/span&gt;&lt;span style="color:blue"&gt;="&lt;/span&gt;&lt;span style="color:blue"&gt;0:0:0.5&lt;/span&gt;&lt;span style="color:blue"&gt;"&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;      &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;Storyboard&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;        &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;ColorAnimation&lt;/span&gt;&lt;span style="color:red"&gt; Storyboard.TargetName&lt;/span&gt;&lt;span style="color:blue"&gt;="tickBox"&lt;/span&gt;
                     &lt;span style="color:red"&gt; Storyboard.TargetProperty&lt;/span&gt;&lt;span style="color:blue"&gt;="(Rectangle.Fill).&lt;/span&gt;
&lt;span style="color:blue"&gt;                      (SolidColorBrush.Color)"&lt;/span&gt;
                     &lt;span style="color:red"&gt; To&lt;/span&gt;&lt;span style="color:blue"&gt;="Red"&lt;/span&gt;&lt;span style="color:red"&gt; Duration&lt;/span&gt;&lt;span style="color:blue"&gt;="0:0:0.5" /&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;      &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color:brown"&gt;Storyboard&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;    &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color:brown"&gt;vsm&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:brown"&gt;VisualTransition&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;  &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color:brown"&gt;vsm&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:brown"&gt;VisualStateGroup.Transitions&lt;/span&gt;&lt;span style="color:blue"&gt;&amp;gt;&lt;/span&gt;
&lt;span style="color:brown"&gt;  &lt;/span&gt;&lt;span style="color:blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:brown"&gt;vsm&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:brown"&gt;VisualState&lt;/span&gt;&lt;span style="color:red"&gt; x&lt;/span&gt;&lt;span style="color:blue"&gt;:&lt;/span&gt;&lt;span style="color:red"&gt;Name&lt;/span&gt;&lt;span style="color:blue"&gt;="MouseOver"&amp;gt;&lt;/span&gt;
    ... as before ...
&lt;/pre&gt;
&lt;p&gt;This has a &lt;code&gt;VisualStateGroup&lt;/code&gt; for the &lt;code&gt;CommonStates&lt;/code&gt; group as before, but I’ve added a &lt;code&gt;Transitions&lt;/code&gt; property. Inside this I’ve added a &lt;code&gt;VisualTransition&lt;/code&gt; defining an extra animation to be run prior to the animation for the &lt;code&gt;Normal&lt;/code&gt; state if we are coming into that state from the &lt;code&gt;Pressed&lt;/code&gt; state.&lt;/p&gt;
&lt;p&gt;So if the user presses the button down on the &lt;code&gt;CheckBox&lt;/code&gt;, and then moves away before letting go, the check box will briefly go red thanks to this transition animation, and then the &lt;code&gt;Normal&lt;/code&gt; state animation will run, returning the control back to its standard appearance.&lt;/p&gt;
&lt;p&gt;Note that you are allowed to leave off either the To, or From attributes from a &lt;code&gt;VisualTransition&lt;/code&gt;. This turns it into a kind of wildcard transition. With just a From attribute, the transition will run any time moving from the named state. With just a To attribute, it will run any time moving to the named state.&lt;/p&gt;
&lt;p&gt;You may wonder what is the point of a transition animation with just a To attribute. What does that offer that I can’t do more easily with a normal &lt;code&gt;VisualState&lt;/code&gt; animation? Well there is one subtle but useful difference. &lt;code&gt;VisualState&lt;/code&gt; animations run any time a state is entered, &lt;i&gt;even when the control first appears&lt;/i&gt;. Transition animations do not. Consider our checkbox example – you might want the tick to fade in and out rather than coming and going abruptly. You could get that effect by adding a non-zero duration to the &lt;code&gt;VisualState&lt;/code&gt; animation for the &lt;code&gt;Checked&lt;/code&gt; state shown earlier. However, if the checkbox happened to be checked when it first appeared, the animation would run then too, which might not be what you want. By contrast, a transition animation with To="Checked" will not run when the control first appears, but will run any time the control enters the Checked state from some other state.&lt;/p&gt;
&lt;p&gt;You can even leave off both To and From, in which case the transition will be inserted before every state change for that state group.&lt;/p&gt;
&lt;h3&gt;Designer Support&lt;/h3&gt;
&lt;p&gt;In summary, you get to define animations that run when the control enters a particular state, and you may also define specialized transition animations that run just before the main animation. It’s certainly different from WPF’s trigger mechanisms, and while it lets you achieve a lot of the same goals, it’s not quite as flexible – you only get to write state animations for the visual states the control author has decided to offer, whereas triggers can use any property.&lt;/p&gt;
&lt;p&gt;However, there’s one thing visual states do better than triggers: designer support. That’s not to say that WPF triggers aren’t supported by Blend – it does in fact support them. But you have to work harder with triggers. The benefit of the visual state model is that Blend can see exactly what states a control offers, and it can help a visual designer fill in all the necessary pieces. By contrast, triggers are so flexible that it’s difficult for a design tool to know where to start.&lt;/p&gt;
&lt;p&gt;If you’re happy cranking out Xaml by hand, you’ll probably miss triggers. But if you live in Blend, visual states offer useful benefits.&lt;/p&gt;
&lt;h3&gt;Learn More about Silverlight (Gratuitous Plug)&lt;/h3&gt;
&lt;p&gt;If you want to learn more about Silverlight, &lt;a href="http://www.pluralsight.com/"&gt;Pluralsight&lt;/a&gt; offers a couple of courses, for which I’m a co-author and instructor. There’s our main &lt;a href="http://www.pluralsight.com/courses/AppliedSilverlight.aspx"&gt;Silverlight course&lt;/a&gt;, recently updated for the Beta 2 release. And we also offer a dual feature &lt;a href="http://www.pluralsight.com/courses/DoubleFeatureAjaxSilverlight.aspx"&gt;Silverlight/ASP.NET Ajax course&lt;/a&gt;, running for more hours in the day and for more days, in which we cover both Silverlight and also ASP.NET Ajax. &lt;/p&gt;</description></item><item><title>Applied WPF Demos from London</title><guid isPermaLink="true">http://www.interact-sw.co.uk/iangblog/2008/05/13/wpf-demos-london</guid><link>http://www.interact-sw.co.uk/iangblog/2008/05/13/wpf-demos-london</link><pubDate>Tue, 13 May 2008 15:25:15 GMT</pubDate><description>&lt;p&gt;My apologies to everyone who attended my WPF course in London last month - it looks like I forgot to upload the demos. I'm afraid I confused myself by putting the wrong title on the previous week's demos...until today the &lt;a href="http://www.interact-sw.co.uk/iangblog/2008/04/03/silverlight-demos-london"&gt;Silverlight demos&lt;/a&gt; from the previous week had a title claiming to be WPF demos. Oops.&lt;/p&gt;
&lt;p&gt;So here, at least are the &lt;a href="http://www.interact-sw.co.uk/downloads/WpfDemosLondon2008-04.zip"&gt;WPF demos&lt;/a&gt; from the &lt;a href="http://www.pluralsight.com/courses/AppliedWPF.aspx"&gt;WPF course&lt;/a&gt; I ran last month.&lt;/p&gt;</description></item><item><title>Deep Zoom at the BBC</title><guid isPermaLink="true">http://www.interact-sw.co.uk/iangblog/2008/05/10/bbc-deep-zoom</guid><link>http://www.interact-sw.co.uk/iangblog/2008/05/10/bbc-deep-zoom</link><pubDate>Sat, 10 May 2008 14:45:50 GMT</pubDate><description>&lt;p&gt;The &lt;a href="http://www.bbc.co.uk/radio1/bigweekend/2008/zoom/"&gt;BBC has a Silverlight deep zoom app&lt;/a&gt; as part of the web coverage of the &lt;a href="http://www.bbc.co.uk/radio1/bigweekend/"&gt;‘Radio 1 Big Weekend’&lt;/a&gt; event. (“Europe’s biggest free ticketed event” apparently.) If you live in the UK and have watched BBC television at all this week, you’ve probably already seen the adverts for the event itself.&lt;/p&gt;
&lt;p&gt;The deep zoom app provides a flavour of the event for people who can’t turn up in person – photos of the event will be uploaded throughout the weekend. (And I guess people who did go could try and find themselves in the crowd shots next week.)&lt;/p&gt;
&lt;p&gt;From a technical perspective, it’s nothing you won’t already have seen if you’ve looked at the &lt;a href="http://memorabilia.hardrock.com/"&gt;Hard Rock Cafe’s memorabilia site&lt;/a&gt; – indeed, the BBC app is somewhat simpler. The main difference is that the BBC’s photo collection that will grow as the event unfolds – not quite live of course, but a bit less static than the Hard Rock application. (And more raw for it of course, but that’s probably in keeping with the nature of the event.)&lt;/p&gt;
&lt;h3&gt;Deep Zoom and Photo Collections&lt;/h3&gt;
&lt;p&gt;What I find interesting is that I like this way of browsing photos &lt;i&gt;much&lt;/i&gt; more than I thought I would. Deep zoom is definitely one of the more conspicuously fun features of Silverlight 2, but as it’s ultimately a bit of a one-trick pony, I thought I’d be pretty much done with it after playing with the Hard Rock demo.&lt;/p&gt;
&lt;p&gt;But it turns out still to be growing on me long after the initial ‘ooh’ factor. I think it’s a surprisingly natural way to present photographs.&lt;/p&gt;
&lt;p&gt;I just went to &lt;a href="http://www.flickr.com/"&gt;flickr&lt;/a&gt;, and coincidentally enough the first picture it showed me on the front page was &lt;a href="http://www.flickr.com/photos/notsogoodphotography/503637906/"&gt;a shot from a concert&lt;/a&gt;. It’s a good picture, but wow the user interface feels flat! Having got used to the deep zoom style of photo browsing, flickr now feels positively broken.&lt;/p&gt;
&lt;p&gt;So I want deep zoom for my online photo collections please!&lt;/p&gt;</description></item><item><title>Nulls and Lifting Member Access</title><guid isPermaLink="true">http://www.interact-sw.co.uk/iangblog/2008/04/13/member-lifting</guid><link>http://www.interact-sw.co.uk/iangblog/2008/04/13/member-lifting</link><pubDate>Sun, 13 Apr 2008 17:30:31 GMT</pubDate><description>&lt;p&gt;Nulls can complicate code. One of the lesser known C# language features, &lt;a href="http://msdn2.microsoft.com/library/ms173224.aspx"&gt;the ?? operator&lt;/a&gt;, can sometimes help. This operator lets you provide an alternate value to be used in the event that an expression evaluates to null. For example:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;string&lt;/span&gt; displayName = elem.Name ?? "[Unknown]";
&lt;/pre&gt;
&lt;p&gt;If &lt;code&gt;elem.Name&lt;/code&gt; evaluates to anything other than null, then &lt;code&gt;displayName&lt;/code&gt; will be &lt;code&gt;elem.Name&lt;/code&gt;. But if &lt;code&gt;elem.Name&lt;/code&gt; is null, &lt;code&gt;displayName&lt;/code&gt; will become &lt;code&gt;"[Unknown]"&lt;/code&gt;. To get the same result in C# 1 requires the cryptic but useful &lt;a href="http://msdn2.microsoft.com/library/ty67wk28.aspx"&gt;ternary operator (aka conditional operator)&lt;/a&gt; (‘Confusing C family language newbies since 1978’). The result is longer, and requires you to write out the expression twice:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;string&lt;/span&gt; displayName = elem.Name == &lt;span style="color:blue"&gt;null&lt;/span&gt; ? "[Unknown]" : elem.Name;
&lt;/pre&gt;
&lt;p&gt;In my experience, most C# developers don’t seem to know about ??. In my &lt;a href="http://www.pluralsight.com/courses/appliedWPF.aspx"&gt;Applied WPF&lt;/a&gt; course, one of the labs uses it in passing, and I invariably get people either asking me what it does, or occasionally telling me it’s a typo!&lt;/p&gt;
&lt;p&gt;People usually like it once they get it, because it’s a clear improvement for this sort of example. So why isn’t it better known? I have a theory: I think it’s less useful than it seems. It only solves one specific example of the ‘nulls are a pain’ class of problems. Most of the time, I want something slightly more powerful than ??.&lt;/p&gt;
&lt;h3&gt;What I’d Like&lt;/h3&gt;
&lt;p&gt;While I frequently have to deal with values that might be null, I’ve found that in the non-null case I usually want to work with a member of the object, rather than the object itself. For example, consider this very simple singly-linked list node:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;public&lt;/span&gt; &lt;span style="color:blue"&gt;class&lt;/span&gt; &lt;span style="color:dimgray"&gt;Node&lt;/span&gt;
{
    &lt;span style="color:blue"&gt;public&lt;/span&gt; &lt;span style="color:dimgray"&gt;Node&lt;/span&gt; Next;
    &lt;span style="color:blue"&gt;public&lt;/span&gt; &lt;span style="color:blue"&gt;string&lt;/span&gt; Value;
}
&lt;/pre&gt;
&lt;p&gt;Suppose you have a variable of type &lt;code&gt;Node&lt;/code&gt; which may be null, and that you want to return the &lt;code&gt;Value&lt;/code&gt; if the variable’s non-null, and return null otherwise. You can’t use the &lt;code&gt;??&lt;/code&gt; operator here – you have to revert to the good old ternary operator:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:dimgray"&gt;Node&lt;/span&gt; n = GetNode();
&lt;span style="color:blue"&gt;string&lt;/span&gt; value = n == &lt;span style="color:blue"&gt;null&lt;/span&gt; ? &lt;span style="color:blue"&gt;null&lt;/span&gt; : n.Value;
&lt;/pre&gt;
&lt;p&gt;This is tolerable, but it’s a case that comes up often enough that I can see the value in having a special syntax to handle it. Sadly, the &lt;code&gt;??&lt;/code&gt; operator is not that syntax – it only seems to cover a small minority of the cases.&lt;/p&gt;
&lt;p&gt;A different solution suggests itself when you look at another feature added in C# 2: lifting for nullable types.&lt;/p&gt;
&lt;h3&gt;Lifting&lt;/h3&gt;
&lt;p&gt;Lifting in C# is a convenient way of working with values that might be null: rather than crashing when you try and use a null value, the nullness just ends up propagating. For example, C# supports lifting when adding numbers together:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;public&lt;/span&gt; &lt;span style="color:blue"&gt;static&lt;/span&gt; &lt;span style="color:blue"&gt;int&lt;/span&gt;? Add(&lt;span style="color:blue"&gt;int&lt;/span&gt;? x, &lt;span style="color:blue"&gt;int&lt;/span&gt;? y)
{
    &lt;span style="color:blue"&gt;return&lt;/span&gt; x + y;
}
&lt;/pre&gt;
&lt;p&gt;If you call this function with integers, it will add them as expected. But you can pass in null for either argument, in which case the result will be null. So we say that the + operator is lifted. (See &lt;a href="http://blogs.msdn.com/ericlippert/default.aspx"&gt;Eric Lippert’s&lt;/a&gt; description of &lt;a href="http://blogs.msdn.com/ericlippert/archive/2007/06/27/what-exactly-does-lifted-mean.aspx"&gt;lifting in C#&lt;/a&gt; for more information.)&lt;/p&gt;
&lt;p&gt;Not all operators are lifted in C#. The arithmetic ones are, so you can perform numeric calculations with nullable types. But many are not. Member access is not lifted, for example. If it were, I’d be able to replace this:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;string&lt;/span&gt; value = n == &lt;span style="color:blue"&gt;null&lt;/span&gt; ? &lt;span style="color:blue"&gt;null&lt;/span&gt; : n.Value;
&lt;/pre&gt;
&lt;p&gt;with this:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;string&lt;/span&gt; value = n.Value;
&lt;/pre&gt;
&lt;p&gt;If ‘.’ were lifted, &lt;code&gt;value&lt;/code&gt; would end up as null if either n itself were null, or the &lt;code&gt;Value&lt;/code&gt; member of the object referred to by n were null.&lt;/p&gt;
&lt;p&gt;This seems like a much more succinct way to deal with the problem, but of course that’s not what ‘.’ does in practice. Morever, we cannot overload ‘.’ in C#, so on the face of it, it seems that only the C# compiler team would be able to make this work. However, we can achieve something close by getting the relevant code into expression tree form, and then modifying the tree.&lt;/p&gt;
&lt;h3&gt;Expression Tree Rewriting&lt;/h3&gt;
&lt;p&gt;&lt;a href="http://msdn2.microsoft.com/library/bb397951.aspx"&gt;C# can convert an expression into tree of objects&lt;/a&gt;. This means we can change how an expression works by simply changing the tree. We could use that to modify the behaviour of ‘.’ to add lifting.&lt;/p&gt;
&lt;p&gt;(This idea is pretty similar to LISP’s macro system – code rewriting expressions or generating new ones. There’s a significant difference though: LISP macros run at compile time. As far as I can tell, we don’t have that option with expression trees in C# 3. However, even though we are obliged to wait until runtime to perform the tree rewriting, we do get to compile the result into IL. So after the initial overhead, the performance should be identical to normally compiled code.)&lt;/p&gt;
&lt;p&gt;One slight snag is that expression trees are immutable. So you can’t just change them – you end up having to build a new tree. Fortunately, Microsoft provides an example class in the documentation that helps you do this: &lt;a href="http://msdn2.microsoft.com/library/bb882521.aspx"&gt;ExpressionVisitor&lt;/a&gt;. This walks every node in an expression tree, and lets you build an edited copy. And it’s smart about unchanged subtrees – it just reuses those rather than copying them. (That’s one of the advantages of immutability – it’s safe to reuse objects like that because you know they’re not going to change.)&lt;/p&gt;
&lt;p&gt;The following class derives from the &lt;code&gt;ExpressionVisitor&lt;/code&gt; example, and overrides &lt;code&gt;VisitMemberAccess&lt;/code&gt; to change the way member access works:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;public&lt;/span&gt; &lt;span style="color:blue"&gt;class&lt;/span&gt; &lt;span style="color:dimgray"&gt;NullLiftModifier&lt;/span&gt; : &lt;span style="color:dimgray"&gt;ExpressionVisitor&lt;/span&gt;
{
&lt;span style="color:green"&gt;  // The method that kicks off the tree walk is&lt;/span&gt;
&lt;span style="color:green"&gt;  // protected, so we need to define a public&lt;/span&gt;
&lt;span style="color:green"&gt;  // method that provides access to it.&lt;/span&gt;
  &lt;span style="color:blue"&gt;public&lt;/span&gt; &lt;span style="color:dimgray"&gt;Expression&lt;/span&gt; Modify(&lt;span style="color:dimgray"&gt;Expression&lt;/span&gt; expression)
  {
    &lt;span style="color:blue"&gt;return&lt;/span&gt; Visit(expression);
  }


&lt;span style="color:green"&gt;  // Change how '.' performs member access.&lt;/span&gt;
  &lt;span style="color:blue"&gt;protected&lt;/span&gt; &lt;span style="color:blue"&gt;override&lt;/span&gt; &lt;span style="color:dimgray"&gt;Expression&lt;/span&gt; VisitMemberAccess(
               &lt;span style="color:dimgray"&gt;MemberExpression&lt;/span&gt; originalExpression)
  {
    &lt;span style="color:dimgray"&gt;MemberExpression&lt;/span&gt; memberAccessExpression =
     (&lt;span style="color:dimgray"&gt;MemberExpression&lt;/span&gt;) &lt;span style="color:blue"&gt;base&lt;/span&gt;.VisitMemberAccess(originalExpression);


    &lt;span style="color:dimgray"&gt;Expression&lt;/span&gt; nullTest = &lt;span style="color:dimgray"&gt;Expression&lt;/span&gt;.Equal(
        memberAccessExpression.Expression,
        &lt;span style="color:dimgray"&gt;Expression&lt;/span&gt;.Constant(&lt;span style="color:blue"&gt;null&lt;/span&gt;,
          memberAccessExpression.Expression.Type));
    &lt;span style="color:blue"&gt;return&lt;/span&gt; &lt;span style="color:dimgray"&gt;Expression&lt;/span&gt;.Condition(
        nullTest,
        &lt;span style="color:dimgray"&gt;Expression&lt;/span&gt;.Constant(&lt;span style="color:blue"&gt;null&lt;/span&gt;, memberAccessExpression.Type),
        memberAccessExpression);
  }
}

&lt;/pre&gt;
&lt;p&gt;The call to the base class builds the expression we’re about to rewrite (possibly recursively rewriting some of its sub expressions.) We then generate some extra expressions to test the target object reference for null, and then to return either a null constant or the original expression, depending on whether the target reference is null. Or to put it in code, it changes this:&lt;/p&gt;
&lt;pre&gt;obj.Member
&lt;/pre&gt;
&lt;p&gt;to this:&lt;/p&gt;
&lt;pre&gt;obj == &lt;span style="color:blue"&gt;null&lt;/span&gt; ? &lt;span style="color:blue"&gt;null&lt;/span&gt; : obj.Member
&lt;/pre&gt;
&lt;p&gt;For ease of use, we can wrap this rewriter in a helper function that takes an expression, rewrites it, and then compiles the result:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;static&lt;/span&gt; &lt;span style="color:dimgray"&gt;Func&lt;/span&gt;&amp;lt;T, TResult&amp;gt; LiftMemberAccessToNull&amp;lt;T, TResult&amp;gt;(
    &lt;span style="color:dimgray"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color:dimgray"&gt;Func&lt;/span&gt;&amp;lt;T, TResult&amp;gt;&amp;gt; expr)
{
    &lt;span style="color:dimgray"&gt;NullLiftModifier&lt;/span&gt; modifier = &lt;span style="color:blue"&gt;new&lt;/span&gt; &lt;span style="color:dimgray"&gt;NullLiftModifier&lt;/span&gt;();
    &lt;span style="color:blue"&gt;var&lt;/span&gt; x = (&lt;span style="color:dimgray"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color:dimgray"&gt;Func&lt;/span&gt;&amp;lt;T, TResult&amp;gt;&amp;gt;) modifier.Modify(expr);
    &lt;span style="color:blue"&gt;return&lt;/span&gt; x.Compile();
}
&lt;/pre&gt;
&lt;p&gt;The compilation here will happen at runtime – &lt;code&gt;Compile&lt;/code&gt; turns the expression tree into IL in a dynamically generated method, and returns a delegate pointing to that method.&lt;/p&gt;
&lt;p&gt;To test this, I wrote the following, which uses the &lt;code&gt;Node&lt;/code&gt; class introduced earlier:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;var&lt;/span&gt; get0 = LiftMemberAccessToNull((&lt;span style="color:dimgray"&gt;Node&lt;/span&gt; f) =&amp;gt; f.Value);
&lt;span style="color:blue"&gt;var&lt;/span&gt; get1 = LiftMemberAccessToNull((&lt;span style="color:dimgray"&gt;Node&lt;/span&gt; f) =&amp;gt; f.Next.Value);
&lt;span style="color:blue"&gt;var&lt;/span&gt; get2 = LiftMemberAccessToNull((&lt;span style="color:dimgray"&gt;Node&lt;/span&gt; f) =&amp;gt; f.Next.Next.Value);
&lt;span style="color:blue"&gt;var&lt;/span&gt; get3 = LiftMemberAccessToNull((&lt;span style="color:dimgray"&gt;Node&lt;/span&gt; f) =&amp;gt; f.Next.Next.Next.Value);
&lt;/pre&gt;
&lt;p&gt;So we have four methods, which pick out the value of the current node, the next node, the node after that, and finally the node after that. I’m using the ordinary member access syntax, but I’m calling the code I wrote earlier to add lifting to the ‘.’ operator. To test these methods, I wrote the following (which, just for fun/added confusion, uses the ?? operator to help print out the results):&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:dimgray"&gt;Node&lt;/span&gt; f1 = &lt;span style="color:blue"&gt;new&lt;/span&gt; &lt;span style="color:dimgray"&gt;Node&lt;/span&gt; { Value = &lt;span style="color:brown"&gt;"One"&lt;/span&gt; };
&lt;span style="color:dimgray"&gt;Node&lt;/span&gt; f2 = &lt;span style="color:blue"&gt;new&lt;/span&gt; &lt;span style="color:dimgray"&gt;Node&lt;/span&gt; { Value = &lt;span style="color:brown"&gt;"Two"&lt;/span&gt; };
&lt;span style="color:dimgray"&gt;Node&lt;/span&gt; f3 = &lt;span style="color:blue"&gt;new&lt;/span&gt; &lt;span style="color:dimgray"&gt;Node&lt;/span&gt; { Value = &lt;span style="color:brown"&gt;"Three"&lt;/span&gt; };
f1.Next = f2; f2.Next = f3;

&lt;span style="color:dimgray"&gt;Node&lt;/span&gt;[] foos = { f1, f2, f3, &lt;span style="color:blue"&gt;null&lt;/span&gt; };
&lt;span style="color:blue"&gt;foreach&lt;/span&gt; (&lt;span style="color:dimgray"&gt;Node&lt;/span&gt; f &lt;span style="color:blue"&gt;in&lt;/span&gt; foos)
{
  &lt;span style="color:dimgray"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:brown"&gt;"Value: "&lt;/span&gt;&lt;span style="color:brown"&gt;               &lt;/span&gt; + (get0(f) ?? &lt;span style="color:brown"&gt;"null"&lt;/span&gt;));
  &lt;span style="color:dimgray"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:brown"&gt;"Next.Value: "&lt;/span&gt;           + (get1(f) ?? &lt;span style="color:brown"&gt;"null"&lt;/span&gt;));
  &lt;span style="color:dimgray"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:brown"&gt;"Next.Next.Value: "&lt;/span&gt;      + (get2(f) ?? &lt;span style="color:brown"&gt;"null"&lt;/span&gt;));
  &lt;span style="color:dimgray"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:brown"&gt;"Next.Next.Next.Value: "&lt;/span&gt; + (get3(f) ?? &lt;span style="color:brown"&gt;"null"&lt;/span&gt;));

  &lt;span style="color:dimgray"&gt;Console&lt;/span&gt;.WriteLine();
}
&lt;/pre&gt;
&lt;p&gt;This builds a list with three nodes, and iterates through this list, trying all four get methods on each of the nodes.&lt;/p&gt;
&lt;p&gt;Normally, you’d expect this to throw a null reference exception. If you have a reference ‘f’ to the first node, the expression &lt;code&gt;f.Next.Next.Next.Value&lt;/code&gt; is looking for the fourth node (i.e. three along from the first). There are only three nodes, so that final &lt;code&gt;Next&lt;/code&gt; will evaluate to null. Normally you’d expect the attempt to access &lt;code&gt;Value&lt;/code&gt; to throw an exception. But we’ve run these expressions through my lifting rewriter, so instead, we see this:&lt;/p&gt;
&lt;pre&gt;Value: One
Next.Value: Two
Next.Next.Value: Three
Next.Next.Next.Value: null

Value: Two
Next.Value: Three
Next.Next.Value: null
Next.Next.Next.Value: null

Value: Three
Next.Value: null
Next.Next.Value: null
Next.Next.Next.Value: null

Value: null
Next.Value: null
Next.Next.Value: null
Next.Next.Next.Value: null
&lt;/pre&gt;
&lt;p&gt;This illustrates that the lifting is working as desired. This is consistent with the + operator: adding null to a number gives you null; likewise here, when I try to access a member via a null reference I get back null.&lt;/p&gt;
&lt;h3&gt;Limitations&lt;/h3&gt;
&lt;p&gt;One big problem with this is that it’s pretty clunky. I have to wrap up the member access in a lambda, and then pass it to my function to get it rewritten and compiled. If I want to make sure I perform that step just the first time my code runs, and yet I still want my lambdas to have access to local variables in scope, the code’s going to get even uglier. So while it might be a neat trick to illustrate the idea, I don’t see myself using this in production code.&lt;/p&gt;
&lt;p&gt;This is a shame, because the idea of rewriting expressions is a pretty powerful one. Lifting member access is only one example of what you can do with this technique. It would be great if there were a clean syntax for this sort of idea.&lt;/p&gt;
&lt;p&gt;(Also, beware that I’ve not tested this in any serious way – it’s only intended to illustrate an idea. It’s probably full of subtle flaws as well as the more glaring issues. I suspect it doesn’t play nicely with &lt;code&gt;Nullable&amp;lt;T&amp;gt;&lt;/code&gt;, for example. Please don’t use it as is in your production code! That said, I offer this code under the &lt;a href="http://opensource.org/licenses/mit-license.php"&gt;MIT license&lt;/a&gt;, so feel free to do what you will with it within the terms of the license. Just consider yourself warned. You can grab the source from here: &lt;a href="http://www.interact-sw.co.uk/downloads/LiftMemberAccess.zip"&gt;http://www.interact-sw.co.uk/downloads/LiftMemberAccess.zip&lt;/a&gt;)&lt;/p&gt;
&lt;h3&gt;A Monadic Footnote&lt;/h3&gt;
&lt;p&gt;When I first started to look at this, I had been considering a slightly different approach. The idea of a nullable value (whether it’s a &lt;a href="http://msdn2.microsoft.com/library/b3h38hb0.aspx"&gt;Nullable&amp;lt;T&amp;gt;&lt;/a&gt; or just an ordinary reference) is pretty similar to Haskell’s &lt;a href="http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-Maybe.html"&gt;Maybe&lt;/a&gt; type. I can use &lt;code&gt;Maybe&lt;/code&gt; to write a Haskell equivalent to the &lt;code&gt;Add&lt;/code&gt; function I wrote in C# above:&lt;/p&gt;
&lt;pre&gt;addMaybe :: Maybe Integer -&amp;gt; Maybe Integer -&amp;gt; Maybe Integer
addMaybe x y =
  do
    xVal &amp;lt;- x
    yVal &amp;lt;- y
    return (xVal + yVal)
&lt;/pre&gt;
&lt;p&gt;This is slightly long-winded, because in Haskell, the addition operator is &lt;i&gt;not&lt;/i&gt; suitably lifted – it doesn’t recognize &lt;a href="http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-Maybe.html"&gt;Maybe&lt;/a&gt; types. (I could arrange for this lifting to happen in Haskell by plugging the code above into the right place and doing some other extra work, incidentally. But this entry’s long enough already.) So I had to write code to explicitly extract the values. A slightly closer C# version might look like this:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:green"&gt;// Note: doesn't work&lt;/span&gt;&lt;span style="color:green"&gt; properly&lt;/span&gt;&lt;span style="color:green"&gt;!&lt;/span&gt;
&lt;span style="color:blue"&gt;public&lt;/span&gt; &lt;span style="color:blue"&gt;static&lt;/span&gt; &lt;span style="color:blue"&gt;int&lt;/span&gt;? AddNullable(&lt;span style="color:blue"&gt;int&lt;/span&gt;? x, &lt;span style="color:blue"&gt;int&lt;/span&gt;? y)
{
    &lt;span style="color:blue"&gt;int&lt;/span&gt; xVal = x.Value;
    &lt;span style="color:blue"&gt;int&lt;/span&gt; yVal = y.Value;
    &lt;span style="color:blue"&gt;return&lt;/span&gt; xVal + yVal;
}
&lt;/pre&gt;
&lt;p&gt;However, this C# doesn’t work, because we’ve lost the lifting – it’ll throw an exception if you pass in null for either argument. But the Haskell version works fine, as we can see from this interactive GHCi session:&lt;/p&gt;
&lt;pre&gt;*Main&amp;gt; addMaybe (Just 18) (Just 24)
Just 42
*Main&amp;gt; addMaybe (Just 123) Nothing
Nothing
*Main&amp;gt; addMaybe Nothing (Just 345)
Nothing
*Main&amp;gt; addMaybe Nothing Nothing
Nothing
&lt;/pre&gt;
&lt;p&gt;(Note, ‘&lt;code&gt;Just&lt;/code&gt;’ is a constructor for a &lt;code&gt;Maybe&lt;/code&gt; instance. So &lt;code&gt;(Just 18)&lt;/code&gt; is roughly similar to &lt;code&gt;new Nullable&amp;lt;int&amp;gt;(18)&lt;/code&gt; in C#. And &lt;code&gt;Nothing&lt;/code&gt; constructs a &lt;code&gt;Maybe&lt;/code&gt; that contains no value – it’s more or less like null.)&lt;/p&gt;
&lt;p&gt;This works because &lt;code&gt;Maybe&lt;/code&gt; belongs to Haskell’s &lt;a href="http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Monad.html"&gt;Monad&lt;/a&gt; type class. The syntax involving ‘do’ and ‘&amp;lt;-’ is available on monadic types, and in the case of the &lt;code&gt;Maybe&lt;/code&gt; monad, the &amp;lt;- operator provides lifted access to the value inside the &lt;code&gt;Maybe&lt;/code&gt; – if either x or y turn out to contain &lt;code&gt;Nothing&lt;/code&gt; then that whole ‘do’ block will evaluate to &lt;code&gt;Nothing&lt;/code&gt;. (See this allegedly &lt;a href="http://www.haskell.org/tutorial/monads.html"&gt;‘gentle’ introduction to monads&lt;/a&gt; for more information on monads in Haskell.)&lt;/p&gt;
&lt;p&gt;I had been thinking of going down a similar path as a result of reading &lt;a href="http://blogs.msdn.com/wesdyer/archive/2008/01/11/the-marvels-of-monads.aspx"&gt;Wes Dyer’s excellent explanation of monads&lt;/a&gt;. He points out that LINQ uses monadic constructs – the &lt;a href="http://msdn2.microsoft.com/library/bb546168.aspx"&gt;standard SelectMany query operator&lt;/a&gt; is essentially the monadic ‘bind’ operator by another name. He even implements a C# version of &lt;code&gt;Maybe&lt;/code&gt;, and I could perhaps use that to rewrite my C# version roughly like this:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;var&lt;/span&gt; r = &lt;span style="color:blue"&gt;from&lt;/span&gt; xVal &lt;span style="color:blue"&gt;in&lt;/span&gt; x.ToMaybe()
        &lt;span style="color:blue"&gt;from&lt;/span&gt; yVal &lt;span style="color:blue"&gt;in&lt;/span&gt; y.ToMaybe()
        &lt;span style="color:blue"&gt;select&lt;/span&gt; x + y;
&lt;/pre&gt;
&lt;p&gt;Not only does this follow a fairly similar pattern to the Haskell version, it would also offer the same lifting behaviour – it would work correctly in the face of &lt;code&gt;Nothing&lt;/code&gt; (null) values.&lt;/p&gt;
&lt;p&gt;So it occurred to me that I could use this technique to perform the member access lifting I was looking for. Here’s a class that tries to do this by providing some extension methods that effectively define the monadic ‘bind’ operator for references:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;public&lt;/span&gt; &lt;span style="color:blue"&gt;static&lt;/span&gt; &lt;span style="color:blue"&gt;class&lt;/span&gt; &lt;span style="color:dimgray"&gt;NullableExtensions&lt;/span&gt;
{
  &lt;span style="color:blue"&gt;public&lt;/span&gt; &lt;span style="color:blue"&gt;static&lt;/span&gt; V Select&amp;lt;T, V&amp;gt;(&lt;span style="color:blue"&gt;this&lt;/span&gt; T maybeT, &lt;span style="color:dimgray"&gt;Func&lt;/span&gt;&amp;lt;T, V&amp;gt; s)
  {
    &lt;span style="color:blue"&gt;if&lt;/span&gt; (maybeT == &lt;span style="color:blue"&gt;null&lt;/span&gt;) { &lt;span style="color:blue"&gt;return&lt;/span&gt; &lt;span style="color:blue"&gt;default&lt;/span&gt;(V); }
    &lt;span style="color:blue"&gt;return&lt;/span&gt; s(maybeT);
  }

  &lt;span style="color:blue"&gt;public&lt;/span&gt; &lt;span style="color:blue"&gt;static&lt;/span&gt; V SelectMany&amp;lt;T, U, V&amp;gt;(&lt;span style="color:blue"&gt;this&lt;/span&gt; T maybeT,
                          &lt;span style="color:dimgray"&gt;Func&lt;/span&gt;&amp;lt;T, U&amp;gt; k, &lt;span style="color:dimgray"&gt;Func&lt;/span&gt;&amp;lt;T, U, V&amp;gt; s)
  {
    &lt;span style="color:blue"&gt;if&lt;/span&gt; (maybeT == &lt;span style="color:blue"&gt;null&lt;/span&gt;) { &lt;span style="color:blue"&gt;return&lt;/span&gt; &lt;span style="color:blue"&gt;default&lt;/span&gt;(V); }

    U maybeBoundResult = k(maybeT);
    &lt;span style="color:blue"&gt;if&lt;/span&gt; (maybeBoundResult == &lt;span style="color:blue"&gt;null&lt;/span&gt;) { &lt;span style="color:blue"&gt;return&lt;/span&gt; &lt;span style="color:blue"&gt;default&lt;/span&gt;(V); }
    &lt;span style="color:blue"&gt;return&lt;/span&gt; s(maybeT, maybeBoundResult);
  }
}
&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;SelectMany&lt;/code&gt; implementation here just bails out early if it hits a null, and returns null without attempting to evaluate anything that follows. (And &lt;code&gt;Select&lt;/code&gt; does much the same.) Note: I’ve used the phrase ‘maybe’ here to indicate potentially empty values – I’m not actually using Wes’s &lt;code&gt;Maybe&lt;/code&gt; implementation. This particular code snippet stands alone.&lt;/p&gt;
&lt;p&gt;Again, I would recommend NOT using this in production code – it effectively adds standard LINQ query operators to &lt;code&gt;System.Object&lt;/code&gt;, which is probably not a sane thing to do in a real program. But with just that code (I don’t need any of the code from earlier) I can now write this sort of thing:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;int&lt;/span&gt;? two = 2;
&lt;span style="color:blue"&gt;int&lt;/span&gt;? one = 1;
&lt;span style="color:blue"&gt;int&lt;/span&gt;? none = &lt;span style="color:blue"&gt;null&lt;/span&gt;;

&lt;span style="color:blue"&gt;var&lt;/span&gt; twoPlusTwo = &lt;span style="color:blue"&gt;from&lt;/span&gt; x &lt;span style="color:blue"&gt;in&lt;/span&gt; two
                 &lt;span style="color:blue"&gt;from&lt;/span&gt; y &lt;span style="color:blue"&gt;in&lt;/span&gt; two
                 &lt;span style="color:blue"&gt;select&lt;/span&gt; x + y;
&lt;span style="color:dimgray"&gt;Console&lt;/span&gt;.WriteLine(twoPlusTwo);

&lt;span style="color:blue"&gt;var&lt;/span&gt; onePlusNothing = &lt;span style="color:blue"&gt;from&lt;/span&gt; x &lt;span style="color:blue"&gt;in&lt;/span&gt; one
                     &lt;span style="color:blue"&gt;from&lt;/span&gt; y &lt;span style="color:blue"&gt;in&lt;/span&gt; none
                     &lt;span style="color:blue"&gt;select&lt;/span&gt; x + y;
&lt;span style="color:dimgray"&gt;Console&lt;/span&gt;.WriteLine(onePlusNothing);

&lt;span style="color:blue"&gt;var&lt;/span&gt; nothingPlusTwo = &lt;span style="color:blue"&gt;from&lt;/span&gt; x &lt;span style="color:blue"&gt;in&lt;/span&gt; none
                     &lt;span style="color:blue"&gt;from&lt;/span&gt; y &lt;span style="color:blue"&gt;in&lt;/span&gt; two
                     &lt;span style="color:blue"&gt;select&lt;/span&gt; x + y;
&lt;span style="color:dimgray"&gt;Console&lt;/span&gt;.WriteLine(nothingPlusTwo);

&lt;span style="color:blue"&gt;var&lt;/span&gt; onePlusTwoPlusOne = &lt;span style="color:blue"&gt;from&lt;/span&gt; x &lt;span style="color:blue"&gt;in&lt;/span&gt; one
                        &lt;span style="color:blue"&gt;from&lt;/span&gt; y &lt;span style="color:blue"&gt;in&lt;/span&gt; two
                        &lt;span style="color:blue"&gt;from&lt;/span&gt; z &lt;span style="color:blue"&gt;in&lt;/span&gt; one
                        &lt;span style="color:blue"&gt;select&lt;/span&gt; x + y + z;
&lt;span style="color:dimgray"&gt;Console&lt;/span&gt;.WriteLine(onePlusTwoPlusOne);
&lt;/pre&gt;
&lt;p&gt;This prints out results for the calculations that have non-null results, and blank lines for the others. (&lt;code&gt;Console.WriteLine&lt;/code&gt; just prints an empty line when given a null.) So lifted use of nullable types is working. But we can also use this to deal with member access through potentially null references.&lt;/p&gt;
&lt;p&gt;The simplest example of working with member access wouldn’t work if I had only provided the &lt;code&gt;SelectMany&lt;/code&gt; method. I added &lt;code&gt;Select&lt;/code&gt; as well was so it would work even if there were only one &lt;code&gt;from&lt;/code&gt; clause. That lets me write this sort of thing:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;foreach&lt;/span&gt; (&lt;span style="color:blue"&gt;var&lt;/span&gt; item &lt;span style="color:blue"&gt;in&lt;/span&gt; doc.SelectNodes(&lt;span style="color:brown"&gt;"//item"&lt;/span&gt;).Cast&amp;lt;&lt;span style="color:dimgray"&gt;XmlNode&lt;/span&gt;&amp;gt;())
{
    &lt;span style="color:blue"&gt;var&lt;/span&gt; title = &lt;span style="color:blue"&gt;from&lt;/span&gt; attr &lt;span style="color:blue"&gt;in&lt;/span&gt; item.Attributes[&lt;span style="color:brown"&gt;"title"&lt;/span&gt;]
                &lt;span style="color:blue"&gt;select&lt;/span&gt; attr.Value;

    &lt;span style="color:dimgray"&gt;Console&lt;/span&gt;.WriteLine(title);
}
&lt;/pre&gt;
&lt;p&gt;This provides a solution of sorts to the member access problem we started with. I’ve run into this particular example on many occasions – I’ve used an XPath query against an &lt;code&gt;XmlDocument&lt;/code&gt; and need to deal with the fact that some attributes may be missing on some of the elements that came back. (And yes, I could have written a more selective XPath query in this particular case. But when you’re dealing with lots of optional attributes, that gets tedious.) If the ‘title’ attribute is missing on a particular item, the code won’t hit an exception on the &lt;code&gt;attr.Value&lt;/code&gt; expression, because my implementation of &lt;code&gt;Select&lt;/code&gt; chooses not to evaluate the &lt;code&gt;select&lt;/code&gt; clause at all if &lt;code&gt;attr&lt;/code&gt; is null. (And the presence of &lt;code&gt;SelectMany&lt;/code&gt; means the same will be true if I use multiple &lt;code&gt;from&lt;/code&gt; clauses.)&lt;/p&gt;
&lt;p&gt;So it’s a similar result to the expression-tree-based lifting of the ‘.’ operator: I get to write code that attempts to access members via references that may be null without needing an explicit null check. However, the resulting code looks pretty arcane, so again, I don’t think I’d use this in production code. In practice, the problem in this particular example is better solved in C# with an ordinary helper function.&lt;/p&gt;
&lt;h3&gt;Conclusion&lt;/h3&gt;
&lt;p&gt;I’ve used some tricks here to implement a couple of variations on my original theme: trying to avoid writing explicit tests for null references when accessing member variables, by lifting member access over null. Unfortunately, neither solution is pretty, so I consider this experiment an interesting failure. And perhaps that’s to be expected – I’m trying to subvert a fundamental feature of the language that was never designed to be modified. If C# had wanted to make it easy, either ‘.’ would have been overloadable, or the compiler would support compile-time hygienic macros.&lt;/p&gt;
&lt;p&gt;Would I want to see either of those things in C#? I’m not sure I would – I’ve suffered too much ‘clever’ C++ that tries to redefine language behaviours. To be fair, a lot of the horror there was down to how the clunky macro system in C++ is entirely unrelated to the rest of the language. However, some of the horror was with better integrated features, such as the way you can in fact overload member access in C++.&lt;/p&gt;
&lt;p&gt;There’s a lot to be said for a language where code does what it appears to do. It’s normal to spend more time reading code than writing it, and if you need to question fundamentals such as “is that thing that looks like field access really accessing a field?” every time you look at a line of code, that’s going to slow you down massively, and increase the chances of misunderstanding the code.&lt;/p&gt;
&lt;p&gt;It reminds me of a troubleshooting consulting engagement I had years ago. A memory leak turned out to be the result of a couple of ‘clever’ behaviours interacting badly. I still remember the growing expression of disbelief on the developer’s face as I stepped into what looked like a single, straightforward statement, but which turned out to involve no fewer than seven implicit function calls! He had no idea it was doing all that, and he’d written it!&lt;/p&gt;
&lt;p&gt;If I were going to have a syntax that means “get this thing from that object, unless we have a null reference, in which case return null”, I think I’d prefer a new, specialized syntax over a new behaviour for an established syntax.&lt;/p&gt;
&lt;p&gt;So I think I’ll file these under “neat trick; DO NOT USE!”&lt;/p&gt;</description></item><item><title>Applied Silverlight Demos from London</title><guid isPermaLink="true">http://www.interact-sw.co.uk/iangblog/2008/04/03/silverlight-demos-london</guid><link>http://www.interact-sw.co.uk/iangblog/2008/04/03/silverlight-demos-london</link><pubDate>Thu, 03 Apr 2008 17:41:14 GMT</pubDate><description>&lt;p&gt;Thanks to everyone who attended the &lt;a href="http://www.pluralsight.com/courses/AppliedSilverlight.aspx"&gt;Applied
Silverlight&lt;/a&gt; course in London this week. As promised, here are the &lt;a href="http://www.interact-sw.co.uk/downloads/SilverlightLondon2008-04.zip"&gt;demos&lt;/a&gt; built during the week.&lt;/p&gt;</description></item><item><title>LINQ Range Variable Oddness</title><guid isPermaLink="true">http://www.interact-sw.co.uk/iangblog/2008/03/29/linq-range-odd</guid><link>http://www.interact-sw.co.uk/iangblog/2008/03/29/linq-range-odd</link><pubDate>Sat, 29 Mar 2008 14:57:22 GMT</pubDate><description>&lt;p&gt;&lt;a href="http://msmvps.com/blogs/jon.skeet/default.aspx"&gt;Jon Skeet&lt;/a&gt; recently observed that &lt;a href="http://feeds.feedburner.com/~r/JonSkeetCodingBlog/~3/259289753/range-variables-is-it-just-me-that-thinks-they-re-different.aspx"&gt;range variables in LINQ expressions are not like other variables&lt;/a&gt;. A range variable is one like &lt;code&gt;foobar&lt;/code&gt; in the following:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;var&lt;/span&gt; query = &lt;span style="color:blue"&gt;from&lt;/span&gt; foobar &lt;span style="color:blue"&gt;in&lt;/span&gt; source
            &lt;span style="color:blue"&gt;where&lt;/span&gt; foobar &amp;gt; 20
            &lt;span style="color:blue"&gt;select&lt;/span&gt; foobar;
&lt;/pre&gt;
&lt;p&gt;Jon points out that the analogy people often draw – the iteration variable in a &lt;code&gt;foreach&lt;/code&gt; loop – isn’t that close an analogy. I thought it would be interesting to come up with a concrete illustration of the differences.&lt;/p&gt;
&lt;p&gt;Before I start, let me introduce a type:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:dimgray"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color:dimgray"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue"&gt;int&lt;/span&gt;&amp;gt;&amp;gt;
&lt;/pre&gt;
&lt;p&gt;That’s a list of functions. Each function in the list takes no arguments, and returns an integer. Here’s a method that walks through such a list, invokes each function in turn, and prints the result:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;static&lt;/span&gt; &lt;span style="color:blue"&gt;void&lt;/span&gt; PrintValues(&lt;span style="color:dimgray"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color:dimgray"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue"&gt;int&lt;/span&gt;&amp;gt;&amp;gt; funcList)
{
    &lt;span style="color:blue"&gt;foreach&lt;/span&gt; (&lt;span style="color:dimgray"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue"&gt;int&lt;/span&gt;&amp;gt; func &lt;span style="color:blue"&gt;in&lt;/span&gt; funcList)
    {
        &lt;span style="color:dimgray"&gt;Console&lt;/span&gt;.WriteLine(func());
    }
}
&lt;/pre&gt;
&lt;p&gt;I’m going to use this to illustrate some differences between LINQ query expression range variables and &lt;code&gt;foreach&lt;/code&gt; iteration variables.&lt;/p&gt;
&lt;h3&gt;Capturing Variables&lt;/h3&gt;
&lt;p&gt;In order to take a look at these variables, I’m going to capture them in lambdas, so we can poke them about a bit and see what happens. This example iterates through the numbers 1 to 10, building a function that captures the iteration variable each time round:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;var&lt;/span&gt; source = &lt;span style="color:dimgray"&gt;Enumerable&lt;/span&gt;.Range(1, 10);

&lt;span style="color:dimgray"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color:dimgray"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue"&gt;int&lt;/span&gt;&amp;gt;&amp;gt; capturedForeachIterationVariables =
    &lt;span style="color:blue"&gt;new&lt;/span&gt; &lt;span style="color:dimgray"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color:dimgray"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue"&gt;int&lt;/span&gt;&amp;gt;&amp;gt;();
&lt;span style="color:blue"&gt;foreach&lt;/span&gt; (&lt;span style="color:blue"&gt;int&lt;/span&gt; i &lt;span style="color:blue"&gt;in&lt;/span&gt; source)
{
    capturedForeachIterationVariables.Add(() =&amp;gt; i);
}
&lt;/pre&gt;
&lt;p&gt;That lambda (the “&lt;code&gt;() =&amp;gt; i&lt;/code&gt;” expression) denotes a function that takes no arguments (hence the empty ()) and returns the value of &lt;code&gt;i&lt;/code&gt;. And the &lt;code&gt;i&lt;/code&gt; in scope here is the iteration variable of the for each loop.&lt;/p&gt;
&lt;p&gt;We can print out the results using the method I showed earlier:&lt;/p&gt;
&lt;pre&gt;PrintValues(capturedForeachIterationVariables);
&lt;/pre&gt;
&lt;p&gt;And here’s the outcome:&lt;/p&gt;
&lt;pre&gt;10
10
10
10
10
10
10
10
10
10
&lt;/pre&gt;
&lt;p&gt;This illustrates that there is just the one iteration variable. Our list contains 10 functions, all of which captured that one same iteration variable. That’s why they printed out the final value.&lt;/p&gt;
&lt;h3&gt;Per Loop Scope&lt;/h3&gt;
&lt;p&gt;With a slight modification, we can give each lambda its own private variable to capture:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:dimgray"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color:dimgray"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue"&gt;int&lt;/span&gt;&amp;gt;&amp;gt; capturedForeachLocals =
    &lt;span style="color:blue"&gt;new&lt;/span&gt; &lt;span style="color:dimgray"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color:dimgray"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue"&gt;int&lt;/span&gt;&amp;gt;&amp;gt;();
&lt;span style="color:blue"&gt;foreach&lt;/span&gt; (&lt;span style="color:blue"&gt;int&lt;/span&gt; i &lt;span style="color:blue"&gt;in&lt;/span&gt; source)
{
    &lt;span style="color:blue"&gt;int&lt;/span&gt; iLocal = i;
    capturedForeachLocals.Add(() =&amp;gt; iLocal);
}
&lt;/pre&gt;
&lt;p&gt;While &lt;code&gt;i&lt;/code&gt; remains in scope for the entire execution of the loop, &lt;code&gt;iLocal&lt;/code&gt; goes out of scope at the end of each iteration. Consequently, each time round the loop, we create a lambda that captures a different &lt;code&gt;iLocal&lt;/code&gt;. So when we print the results, we see something different:&lt;/p&gt;
&lt;pre&gt;1
2
3
4
5
6
7
8
9
10
&lt;/pre&gt;
&lt;h3&gt;Capturing a Range Variable&lt;/h3&gt;
&lt;p&gt;What about range variables? Here’s the rough equivalent&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;var&lt;/span&gt; query = &lt;span style="color:blue"&gt;from&lt;/span&gt; i &lt;span style="color:blue"&gt;in&lt;/span&gt; source
            &lt;span style="color:blue"&gt;select&lt;/span&gt; ((&lt;span style="color:dimgray"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue"&gt;int&lt;/span&gt;&amp;gt;) (() =&amp;gt; i));

&lt;span style="color:dimgray"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color:dimgray"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue"&gt;int&lt;/span&gt;&amp;gt;&amp;gt; capturedRangeVariables =
    query.ToList();
&lt;/pre&gt;
&lt;p&gt;The syntax is a little messy here because C# is unable to infer the lambda type. Remember, &lt;a href="http://www.interact-sw.co.uk/iangblog/2008/03/17/lambda-inference"&gt;lambda expressions don’t have an intrinsic type&lt;/a&gt;, so the compiler needs more information. In the previous two examples, the compiler was able to infer what was required from the signature of the &lt;code&gt;List&amp;lt;T&amp;gt;.Add&lt;/code&gt; method to which we were passing the lambda. I can’t work out a neat way of giving the compiler what it needs here, so I’ve settled for a rather ugly cast. (I suppose I could also have used a variation on the &lt;code&gt;Funcify&lt;/code&gt; function from &lt;a href="http://www.interact-sw.co.uk/iangblog/2008/03/17/lambda-inference"&gt;that recent blog&lt;/a&gt;, but it doesn’t look much better to me.)&lt;/p&gt;
&lt;p&gt;Anyway, here are the results:&lt;/p&gt;
&lt;pre&gt;1
2
3
4
5
6
7
8
9
10
&lt;/pre&gt;
&lt;p&gt;So the behaviour is not like the &lt;code&gt;foreach&lt;/code&gt; iteration variable – it’s more like the case where we made a copy of the iteration variable. That’s a better analogy, but we can dig a little further.&lt;/p&gt;
&lt;h3&gt;Modifying the Range Variable&lt;/h3&gt;
&lt;p&gt;Expressions in LINQ query expressions can sometimes have side-effects. Whether that’s allowed depends on what flavour of LINQ you’re using. We’re using LINQ to Objects here, and that permits it. Here’s a modified version of the previous query expression:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;var&lt;/span&gt; query = &lt;span style="color:blue"&gt;from&lt;/span&gt; i &lt;span style="color:blue"&gt;in&lt;/span&gt; source
            &lt;span style="color:blue"&gt;select&lt;/span&gt; ((&lt;span style="color:dimgray"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue"&gt;int&lt;/span&gt;&amp;gt;) (() =&amp;gt; ++i)); 

&lt;span style="color:dimgray"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color:dimgray"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue"&gt;int&lt;/span&gt;&amp;gt;&amp;gt; capturedRangeVariables =
    query.ToList();
&lt;/pre&gt;
&lt;p&gt;This increments the captured range variable. Now that won’t interfere with the overall progress of the iteration, because as we already know, the lambda here seems to be working with a copy of &lt;code&gt;i&lt;/code&gt; rather than the ‘real’ &lt;code&gt;i&lt;/code&gt;. So if we print it out once, we get what you’d probably expect:&lt;/p&gt;
&lt;pre&gt;2
3
4
5
6
7
8
9
10
11
&lt;/pre&gt;
&lt;p&gt;And if we print it out the list a second time, as you may or may not have been expecting everything moves up by one:&lt;/p&gt;
&lt;pre&gt;3
4
5
6
7
8
9
10
11
12
&lt;/pre&gt;
&lt;p&gt;(Note, I’m only evaluating the query once – that happens when I call &lt;code&gt;ToList&lt;/code&gt;. And then I’m printing out the resulting list multiple times, and the numbers go up by one each time. If I were to re-evaluate the query, that’d be different. It would build a brand new set of functions that would start back from 2 again.)&lt;/p&gt;
&lt;p&gt;We can represent this as a &lt;code&gt;foreach&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;foreach&lt;/span&gt; (&lt;span style="color:blue"&gt;int&lt;/span&gt; i &lt;span style="color:blue"&gt;in&lt;/span&gt; source)
{
    &lt;span style="color:blue"&gt;int&lt;/span&gt; iLocal = i;
    capturedForeachLocals.Add(() =&amp;gt; ++iLocal);
}
&lt;/pre&gt;
&lt;p&gt;The behaviour is the same. Again, this suggests that LINQ query expression range variables work more like a &lt;i&gt;copy&lt;/i&gt; of a &lt;code&gt;foreach&lt;/code&gt; iteration variable than the iteration variable itself. (Incidentally, if you were to try and use &lt;code&gt;i++&lt;/code&gt; in this &lt;code&gt;foreach&lt;/code&gt; loop, it wouldn’t even compile. C# prevents you from modifying the iteration variable – another way in which iteration variables are different from range variables.)&lt;/p&gt;
&lt;p&gt;But we can go further still.&lt;/p&gt;
&lt;h3&gt;Multiple References to the Range Variable&lt;/h3&gt;
&lt;p&gt;LINQ query expressions can contain many clauses, each of which will often want to access the range variable. This means I can build a query that attempts to modify the range variable in one clause before going on to use it again in a later clause:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;var&lt;/span&gt; query = &lt;span style="color:blue"&gt;from&lt;/span&gt; i &lt;span style="color:blue"&gt;in&lt;/span&gt; source
            &lt;span style="color:blue"&gt;where&lt;/span&gt; ++i &amp;lt; 5
            &lt;span style="color:blue"&gt;select&lt;/span&gt; ((&lt;span style="color:dimgray"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue"&gt;int&lt;/span&gt;&amp;gt;) (() =&amp;gt; i));

&lt;span style="color:dimgray"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color:dimgray"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue"&gt;int&lt;/span&gt;&amp;gt;&amp;gt; capturedRangeVariables =
    query.ToList();
&lt;/pre&gt;
&lt;p&gt;On the face of it, this has a &lt;code&gt;where&lt;/code&gt; clause that increments the range variable, and then only lets through items where the result is less than 5. So we’d expect only to see three items in the output. But what do we expect those output values to be? It would be reasonable expect to that the &lt;code&gt;i&lt;/code&gt; in the &lt;code&gt;select&lt;/code&gt; clause will have the incremented value – after all, it looks like the same variable, &lt;code&gt;i&lt;/code&gt;, that got incremented in the line above. And yet the output is as follows:&lt;/p&gt;
&lt;pre&gt;1
2
3
&lt;/pre&gt;
&lt;p&gt;That is, the &lt;code&gt;i&lt;/code&gt; captured in the &lt;code&gt;select&lt;/code&gt; clause does not seem to have been affected by the increment operator applied to the &lt;code&gt;i&lt;/code&gt; in the &lt;code&gt;where&lt;/code&gt; clause. Clearly the ++ has had an effect – we’ve only got three numbers out, and we would have expected four if that ++ were not present.&lt;/p&gt;
&lt;p&gt;So it’s as though the two clauses are working on different variables, despite being in the same scope and using the same name. The &lt;code&gt;foreach&lt;/code&gt; equivalent looks like this:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;foreach&lt;/span&gt; (&lt;span style="color:blue"&gt;int&lt;/span&gt; i &lt;span style="color:blue"&gt;in&lt;/span&gt; source)
{
    &lt;span style="color:blue"&gt;int&lt;/span&gt; iLocal1 = i;
    &lt;span style="color:blue"&gt;if&lt;/span&gt; (++iLocal1 &amp;lt; 5)
    {
        &lt;span style="color:blue"&gt;int&lt;/span&gt; iLocal2 = i;
        capturedForeachLocals.Add(() =&amp;gt; iLocal2);
    }
}
&lt;/pre&gt;
&lt;h3&gt;Phantom Variables&lt;/h3&gt;
&lt;p&gt;So query expression range variables clearly are quite different from &lt;code&gt;foreach&lt;/code&gt; iteration variables. Each clause in a query expression that refers to the range variable gets its own local variable, so while it may look like one variable, it’s not. And as Jon points out the range variable never really exists in the compiled result – once a query expression is compiled, the only tangible variables in the code are the local copies. And you can see why by manually expanding any of these query expressions out into their equivalent method call forms: you’ll see that the range variable vanishes as part of this transformation.&lt;/p&gt;
&lt;p&gt;So the range variable is really just a label that directs the transformation of a query expression into code at compile time. Once it has done this job, it vanishes.&lt;/p&gt;</description></item><item><title>C# 3.0 Lambdas and Type Inference</title><guid isPermaLink="true">http://www.interact-sw.co.uk/iangblog/2008/03/17/lambda-inference</guid><link>http://www.interact-sw.co.uk/iangblog/2008/03/17/lambda-inference</link><pubDate>Mon, 17 Mar 2008 16:07:32 GMT</pubDate><description>&lt;p&gt;Daniel Cazzulino recently wrote a blog entry whose main focus was on &lt;a href="http://www.clariusconsulting.net/blogs/kzu/archive/2008/01/20/PipelinesUsingIteratorsLambdaExpressionsExtensionMethods.aspx"&gt;building pipelines using iterators in C#&lt;/a&gt;. Towards the end he showed a slightly irritating problem in C# 3.0. He wanted to write this:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;var&lt;/span&gt; transformer = x =&amp;gt; &lt;span style="color:blue"&gt;new&lt;/span&gt; { Original = x, Normalized = x.ToLower() };
&lt;/pre&gt;
&lt;p&gt;However, the C# compiler complains because it doesn’t have enough information to infer the type of the &lt;code&gt;transformer&lt;/code&gt; variable. The problem it reports is “&lt;i&gt;Cannot assign lambda expression to an implicitly-typed local variable&lt;/i&gt;”.&lt;/p&gt;
&lt;p&gt;Daniel doesn’t present a working solution to this particular problem – he ends up structuring his program differently to avoid the issue entirely. But in his discussion of this problem, he proposes something that he describes as ugly, and which, as he points out, doesn’t work anyway:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:dimgray"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue"&gt;string&lt;/span&gt;, {&lt;span style="color:blue"&gt;string&lt;/span&gt; Original, &lt;span style="color:blue"&gt;string&lt;/span&gt; Normalized}&amp;gt; transformer =
   x =&amp;gt; &lt;span style="color:blue"&gt;new&lt;/span&gt; { Original = x, Normalized = x.ToLower() };
&lt;/pre&gt;
&lt;p&gt;This is a direct approach to the problem described in the compiler error message. Can’t assign the expression to an implicitly-typed variable? OK, let’s make the variable explicitly typed. Unfortunately, you can’t specify the type because the expression involves an anonymous type. And that’s the thing about anonymous types: they don’t have names.&lt;/p&gt;
&lt;p&gt;Daniel has made up a plausible syntax for denoting unnamed types: the first part in {} shows a possible solution. But that was just a hypothetical suggestion on his part – in fact C# 3.0 doesn’t provide a way to denote anonymous types.&lt;/p&gt;
&lt;p&gt;But there is a solution. We carry on using an implicitly-typed variable, and fix the expression instead. The error says we can’t use a lambda expression. OK – let’s use something else. And as you’ll see, we don’t even have to get rid of the lambda. We can just wrap it in something.&lt;/p&gt;
&lt;h3&gt;Why Can’t I Use a Lambda?&lt;/h3&gt;
&lt;p&gt;To decide what to use in place of the raw lambda expression, we need to understand &lt;i&gt;why&lt;/i&gt; C# isn’t letting us use a lambda here. The problem is that lambda expressions don’t have an intrinsic type. They’re more adaptable than that – a given lambda expression could mean several different things. The most straightforward demonstration of this is that the exact same expression could evaluate to either a delegate or an expression tree.&lt;/p&gt;
&lt;p&gt;The compiler uses the context to determine the type. If you’re trying to assign or pass the lambda to something expecting a delegate, it’ll turn into a delegate. But if the target expects an expression tree, you’ll get one of those instead.&lt;/p&gt;
&lt;p&gt;In short, a lambda’s expression’s evaluated type is determined by the context in which it’s used.&lt;/p&gt;
&lt;p&gt;This gives us a problem with &lt;code&gt;var&lt;/code&gt;: &lt;code&gt;var&lt;/code&gt; says that its type is determined by the expression with which it is initialized. So when &lt;code&gt;var&lt;/code&gt; meets a lambda, it’s like the two are stood by a doorway, each politely saying “No, after you”. (Apologies to my international readers – I suspect that might be a slightly over-British analogy...)&lt;/p&gt;
&lt;p&gt;Something needs to decide the type. But the obvious approaches (ordinary explicitly-typed variables, or casts) end up hitting the problem Daniel hit: you can’t denote an anonymous type, so how do you specify the type? But it turns out that you don’t need to specify the type completely. All you really need to do is provide just enough information to let the C# compiler proceed.&lt;/p&gt;
&lt;h3&gt;Providing Just Enough Type Information&lt;/h3&gt;
&lt;p&gt;We can narrow down the C# compiler’s options without fully specifying the type. The trick is to go via a function call. Consider this apparently pointless function:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;public&lt;/span&gt; &lt;span style="color:blue"&gt;static&lt;/span&gt; &lt;span style="color:dimgray"&gt;Func&lt;/span&gt;&amp;lt;T, TResult&amp;gt; Funcify&amp;lt;T, TResult&amp;gt;(&lt;span style="color:dimgray"&gt;Func&lt;/span&gt;&amp;lt;T, TResult&amp;gt; f)
{ &lt;span style="color:blue"&gt;return&lt;/span&gt; f; }
&lt;/pre&gt;
&lt;p&gt;What use would that be, you may wonder? It takes any single-parameter function and returns that function without doing anything with or to it!&lt;/p&gt;
&lt;p&gt;However, this provides the C# compiler with a little more information. If I pass a lambda as a parameter to &lt;code&gt;Funcify&lt;/code&gt;, I’ve closed down an option: the C# compiler knows that whatever it produces needs to be a &lt;code&gt;Func&lt;/code&gt; – it no longer has the option to produce an expression tree. This might be enough to disambiguate matters. Unfortunately, it’s not quite enough to fix our example, as we’ll see when we try it:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;var&lt;/span&gt; transformer = Funcify(
      x =&amp;gt; &lt;span style="color:blue"&gt;new&lt;/span&gt; { Original = x, Normalized = x.ToLower() });
&lt;/pre&gt;
&lt;p&gt;This gets rid of the previous error, but replaces it with a new one:&lt;/p&gt;
&lt;p&gt;“&lt;i&gt;The type arguments for method 'Funcit.Program.Funcify&amp;lt;T,TResult&amp;gt;(System.Func&amp;lt;T,TResult&amp;gt;)' cannot be inferred from the usage. Try specifying the type arguments explicitly.&lt;/i&gt;”&lt;/p&gt;
&lt;p&gt;But that’s progress. Honest! The compiler is no longer telling us that we can’t do this with &lt;code&gt;var&lt;/code&gt;. It’s now telling us that it doesn’t have quite enough information.&lt;/p&gt;
&lt;p&gt;The problem here is that it doesn’t know what ‘x’ is. And how could it? Any type with a &lt;code&gt;ToLower&lt;/code&gt; method would do. The intent here is for it to be a string, so we just need to express that:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;var&lt;/span&gt; transformer = Funcify(
      (&lt;span style="color:blue"&gt;string&lt;/span&gt; x) =&amp;gt; &lt;span style="color:blue"&gt;new&lt;/span&gt; { Original = x, Normalized = x.ToLower() });
&lt;/pre&gt;
&lt;p&gt;And now we’re good. The compiler is happy, because we gave just enough information to pin things down and it was able to infer the rest.&lt;/p&gt;
&lt;h3&gt;Mumble Types&lt;/h3&gt;
&lt;p&gt;I’ve seen in some C# team members’ blogs a suggestion for something they call ‘mumble types’. If I’ve understood them correctly, the idea is that you can provide a type specification, but you get to ‘mumble’ (i.e. be unclear) about parts of the type specification. This would give us an alternative solution:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:dimgray"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue"&gt;string&lt;/span&gt;, ?&amp;gt; transformer =
      x =&amp;gt; &lt;span style="color:blue"&gt;new&lt;/span&gt; { Original = x, Normalized = x.ToLower() };
&lt;/pre&gt;
&lt;p&gt;This doesn’t work today, but I would prefer this solution if it were available. It does exactly what I did – it lets me specify just enough to let the compiler’s type inference finish the job – but it doesn’t require the questionable hack of my &lt;code&gt;Funcify&lt;/code&gt; function. And I think it’s clearer – with my example, it’s not particularly obvious that I was trying to fix some parts of the type specification while leaving other parts to be inferred. But with this ‘mumble type’ approach, it’s a lot more obvious that I’m saying ‘I want it to be a Func, and I want the input to be a string, but I want the compiler to infer the Func’s return type’. Also, this approach avoids the clutter of specifying the string type in the lambda parameter list itself, so I find it somewhat more aesthetically pleasing.&lt;/p&gt;
&lt;p&gt;The use of the ‘?’ is based on what I’ve seen in C# team members’ blogs in the past year or two. However, here’s a different syntax to consider:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:dimgray"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue"&gt;string&lt;/span&gt;, &lt;span style="color:blue"&gt;var&lt;/span&gt;&amp;gt; transformer =
      x =&amp;gt; &lt;span style="color:blue"&gt;new&lt;/span&gt; { Original = x, Normalized = x.ToLower() };
&lt;/pre&gt;
&lt;p&gt;We already use the keyword &lt;code&gt;var&lt;/code&gt; to say ‘the compiler should deduce this type’ for variable declarations. So I think it would be consistent to use the same keyword to mean the same thing in partially specified generic types too. That said, the ‘?’ has the benefit of standing out. And it seems reminiscent of Haskell’s use of ‘_’ to mean ‘whatever’. So I could see either approach, but I think I slightly prefer the idea of using &lt;code&gt;var&lt;/code&gt;.&lt;/p&gt;
&lt;h3&gt;Gratuitous Plug for Training in London&lt;/h3&gt;
&lt;p&gt;And finally, some advertising. I’m teaching a couple of training courses for &lt;a href="http://www.pluralsight.com/"&gt;Pluralsight&lt;/a&gt; in London soon. I’ll be running the &lt;a href="http://www.pluralsight.com/courses/AppliedSilverlight.aspx"&gt;Silverlight course&lt;/a&gt; that &lt;a href="http://www.pluralsight.com/fritz.aspx"&gt;Fritz Onion&lt;/a&gt; and I co-author &lt;a href="http://www.pluralsight.com/courses/logistics/London.aspx"&gt;at Old Street&lt;/a&gt; from 31st March to 3rd April. And I’ll be teaching our &lt;a href="http://www.pluralsight.com/courses/AppliedWPF.aspx"&gt;WPF course&lt;/a&gt; at the same location the following week – from 7th to 10th April.&lt;/p&gt;</description></item><item><title>Silverlight 2 Beta 1 Cross Domain Bug</title><guid isPermaLink="true">http://www.interact-sw.co.uk/iangblog/2008/03/16/silverlight-xdomain-semi</guid><link>http://www.interact-sw.co.uk/iangblog/2008/03/16/silverlight-xdomain-semi</link><pubDate>Sun, 16 Mar 2008 15:37:54 GMT</pubDate><description>&lt;p&gt;I recently ran into what appears to be a bug in Silverlight 2 Beta 1’s handling of cross-domain web service access when using a clientaccesspolicy.xml file. I’m hoping this post might save a few other people the time it took me to work out what was going on here.&lt;/p&gt;
&lt;p&gt;Here’s the executive summary: if the web service exposes resources whose URIs contain semicolons, you will not be able to access those resources cross-domain if you’re using clientaccesspolicy.xml. The workaround is to use crossdomain.xml instead. &lt;/p&gt;
&lt;p&gt;Now for the more detailed version.&lt;/p&gt;
&lt;p&gt;In case you’re not familiar with cross-domain web service access, here’s the basic idea. By default, a web browser won’t let client-side code go connecting to any old web site. Client-side code is allowed to make requests against the web site from which it was originally downloaded, and it should only have access to other sites if those sites opt in.&lt;/p&gt;
&lt;p&gt;In pure AJAX sites, this is often achieved using a faintly smelly hack where web services return runnable script rather than simple data. Flash introduced a somewhat more formal mechanism by which a web site can declare that it’s happy to be accessed by client-side code from other domains. Silverlight now supports this feature as of v2 beta 1.&lt;/p&gt;
&lt;p&gt;Here’s an example. If your web site offers a resource called /crossdomain.xml containing this:&lt;/p&gt;
&lt;pre&gt;&amp;lt;!DOCTYPE cross-domain-policy SYSTEM
   "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd"&amp;gt;
&amp;lt;cross-domain-policy&amp;gt;
  &amp;lt;allow-access-from domain="*" /&amp;gt;
&amp;lt;/cross-domain-policy&amp;gt;
&lt;/pre&gt;
&lt;p&gt;the site is declaring that it is open to anyone.&lt;/p&gt;
&lt;p&gt;This policy is enforced on the client side by whatever runtime is performing the cross-domain network activity. Both Flash and Silverlight 2 beta 1 will look for this file when code in these runtimes attempts to access a web site from another domain. (This doesn’t help you from JavaScript, because today, no browser script engine supports this mechanism.)&lt;/p&gt;
&lt;p&gt;One problem with this is that it’s a bit of a blunt instrument. You can be selective about who is allowed to access your site – you don’t have to use a wildcard. But you can’t be selective about what they can access. E.g., I might like to say that only content beneath a particular URI should be accessible to client code that originated from external domains.&lt;/p&gt;
&lt;h3&gt;Selective Cross-Domain Access: clientaccesspolicy.xml&lt;/h3&gt;
&lt;p&gt;As well as supporting Flash’s mechanism, Silverlight 2 beta 1 also introduces a more selective form of cross-domain policy. Before looking for a Flash-style crossdomain.xml resource, Silverlight will look for a clientaccesspolicy.xml file. This has a slightly more complex structure that enables you to constrain what a client can do. Here’s an example:&lt;/p&gt;
&lt;pre&gt;&amp;lt;access-policy&amp;gt;
  &amp;lt;cross-domain-access&amp;gt;
    &amp;lt;policy&amp;gt;
      &amp;lt;allow-from&amp;gt;
        &amp;lt;domain uri="*"/&amp;gt;
      &amp;lt;/allow-from&amp;gt;
      &amp;lt;grant-to&amp;gt;
        &amp;lt;resource path="/extsvc/" include-subpaths="true"/&amp;gt;
      &amp;lt;/grant-to&amp;gt;
    &amp;lt;/policy&amp;gt;
  &amp;lt;/cross-domain-access&amp;gt;
&amp;lt;/access-policy&amp;gt;
&lt;/pre&gt;
&lt;p&gt;This says that clients from any external domain are granted cross-domain access, but it limits it to resources that start with /extsvc/.&lt;/p&gt;
&lt;p&gt;This is a little more flexible than the Flash approach – it lets you make only selected parts of your site available. With crossdomain.xml, you would need to expose services under a distinct domain name to get this selectivity. Obviously that’s not rocket science – it’s certainly possible to present various services under various different domain names. So Silverlight’s approach doesn’t exactly enable anything that was impossible under Flash. On the other hand, this is a whole lot more convenient for people whose web hosting arrangements might not make it so easy to crank up new domain names for each set of services requiring distinct client access policies. And editing a text file is usually a more lightweight process than partitioning a web site’s services across multiple domains.&lt;/p&gt;
&lt;h3&gt;Semicolons Not Welcome in Beta 1&lt;/h3&gt;
&lt;p&gt;Unfortunately, there seems to be a problem in beta 1 of Silverlight. If the service you wish to access has a semicolon in its URI, Silverlight won’t allow your client-side code to access it, no matter what the clientaccesspolicy.xml file says. This is unfortunate if you’re using a service written the way advocated in &lt;a href="http://www.oreilly.com/catalog/9780596529260/"&gt;RESTful Web Services&lt;/a&gt;, which recommends delimiting order-independent parts of a URL with semicolons. And the service I was using did exactly that. It took me a while to work out that it was specifically the semicolons that were causing problems, hence this post.&lt;/p&gt;
&lt;p&gt;This is presumably just a bug in the code that works out whether any particular URI is permitted by the policy. Since the simpler crossdomain.xml grants all-or-nothing access, it never has to examine the URI, so it doesn’t have this problem. That’s why the simpler but less flexible crossdomain.xml offers a workaround here.&lt;/p&gt;
&lt;h3&gt;Learn More about Silverlight 2&lt;/h3&gt;
&lt;p&gt;If you want to learn more about Silverlight, I’ll be teaching the &lt;a href="http://www.pluralsight.com/courses/AppliedSilverlight.aspx"&gt;Silverlight course&lt;/a&gt; that &lt;a href="http://www.pluralsight.com/fritz.aspx"&gt;Fritz Onion&lt;/a&gt; and I co-author for &lt;a href="http://www.pluralsight.com/"&gt;Pluralsight&lt;/a&gt; in London in a couple of weeks. The 4 day course will be &lt;a href="http://www.pluralsight.com/courses/logistics/London.aspx"&gt;running at Old Street&lt;/a&gt; from 31st March to 3rd April. (And I’ll be teaching our &lt;a href="http://www.pluralsight.com/courses/AppliedWPF.aspx"&gt;WPF course&lt;/a&gt; at the same location the following week.)&lt;/p&gt;</description></item><item><title>DevWeek 2008 Cross Platform Silverlight Demos</title><guid isPermaLink="true">http://www.interact-sw.co.uk/iangblog/2008/03/12/devweek-xplat-demos</guid><link>http://www.interact-sw.co.uk/iangblog/2008/03/12/devweek-xplat-demos</link><pubDate>Wed, 12 Mar 2008 18:40:14 GMT</pubDate><description>&lt;p&gt;I just finished the Cross Platform .NET on Silverlight talk at &lt;a href="http://www.devweek.com/"&gt;DevWeek&lt;/a&gt;. Demos can be downloaded from &lt;a href="http://www.interact-sw.co.uk/downloads/DevWeek2008XPlatDemos.zip"&gt;http://www.interact-sw.co.uk/downloads/DevWeek2008XPlatDemos.zip&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;
I'm all done at DevWeek for this year. But if you want to hear more about Silverlight, I'll be teaching Pluralsight's &lt;a href="http://www.pluralsight.com/courses/AppliedSilverlight.aspx"&gt;Applied Silverlight&lt;/a&gt; course in London later this month - running from 31st March. (And the following week I'll be teaching our &lt;a href="http://www.pluralsight.com/courses/AppliedWPF.aspx"&gt;Applied WPF&lt;/a&gt; course, also in London.)
&lt;/p&gt;</description></item></channel></rss>