<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-9201139154426574883</id><updated>2012-01-30T23:46:40.236Z</updated><category term='Sandcastle'/><category term='C++'/><category term='C#'/><category term='Visual Studio'/><category term='Windows Forms'/><category term='Unit Testing'/><category term='WPF'/><category term='Implementing Observable Objects'/><title type='text'>Loads&lt;Code&gt;</title><subtitle type='html'>A technical blog, primarily about .NET development with C#</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://loadsofcode.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://loadsofcode.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Kevin Westhead</name><uri>http://www.blogger.com/profile/05226243485559749240</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/-T93lAVSpKrI/Tu__lq-Ia9I/AAAAAAAAAII/tnKoAeDFrrs/s220/Kevin%2BWesthead%2B%2528grey%2529.jpg'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>20</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-9201139154426574883.post-6336706366065317358</id><published>2009-07-23T23:00:00.000+01:00</published><updated>2009-07-24T11:20:00.122+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='WPF'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><category scheme='http://www.blogger.com/atom/ns#' term='Sandcastle'/><title type='text'>Documenting Attached Properties with Sandcastle</title><content type='html'>&lt;p&gt;I’ve been using &lt;a href="http://www.codeplex.com/Sandcastle"&gt;Sandcastle&lt;/a&gt; and &lt;a href="http://shfb.codeplex.com/"&gt;Sandcastle Help File Builder&lt;/a&gt; (&lt;em&gt;SHFB&lt;/em&gt;) recently to produce some SDK documentation and noticed that topics were automatically created for &lt;a href="http://msdn.microsoft.com/en-us/library/ms749011.aspx"&gt;attached properties&lt;/a&gt; like the one shown &lt;a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.canvas.left.aspx"&gt;here&lt;/a&gt;. But how do you actually populate these topics and how do you link back to them? Well let’s work through a simple example.&lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="remxml"&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;
&lt;span class="remxml"&gt;/// &lt;/span&gt;&lt;span class="rem"&gt;Identifies the MyAttached attached property.&lt;/span&gt;
&lt;span class="remxml"&gt;/// &lt;/span&gt;&lt;span class="remxml"&gt;&amp;lt;/summary&amp;gt;&lt;/span&gt;
&lt;span class="kwrd"&gt;public static readonly&lt;/span&gt; &lt;span class="type"&gt;DependencyProperty&lt;/span&gt; MyAttachedProperty = 
  &lt;span class="type"&gt;DependencyProperty&lt;/span&gt;.RegisterAttached(&lt;span class="str"&gt;&amp;quot;MyAttached&amp;quot;&lt;/span&gt;, &lt;span class="kwrd"&gt;typeof&lt;/span&gt;(&lt;span class="kwrd"&gt;string&lt;/span&gt;), &lt;span class="kwrd"&gt;typeof&lt;/span&gt;(&lt;span class="type"&gt;MyClass&lt;/span&gt;));

&lt;span class="kwrd"&gt;public static string&lt;/span&gt; GetMyAttached(&lt;span class="type"&gt;DependencyObject&lt;/span&gt; element)
{
  &lt;span class="rem"&gt;// Argument validation omitted.&lt;/span&gt;
  &lt;span class="kwrd"&gt;return&lt;/span&gt; (&lt;span class="kwrd"&gt;string&lt;/span&gt;)element.GetValue(MyAttachedProperty);
}

&lt;span class="kwrd"&gt;public static void&lt;/span&gt; SetMyAttached(&lt;span class="type"&gt;DependencyObject&lt;/span&gt; element, &lt;span class="kwrd"&gt;string&lt;/span&gt; value)
{
  &lt;span class="rem"&gt;// Argument validation omitted.&lt;/span&gt;
  element.SetValue(MyAttachedProperty, value);
}&lt;/pre&gt;

&lt;p&gt;With attached properties there’s no physical property in the code for you to document. The only members that can be documented with the code are the dependency property field and the get/set helper methods. So how do you add documentation to the attached property topic? Well you can manually create an additional XML comment file for the assembly containing the attached property and add the following content:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;&amp;lt;?&lt;/span&gt;&lt;span class="html"&gt;xml&lt;/span&gt; &lt;span class="attr"&gt;version&lt;/span&gt;&lt;span class="kwrd"&gt;=&lt;/span&gt;&amp;quot;&lt;span class="kwrd"&gt;1.0&lt;/span&gt;&amp;quot;&lt;span class="kwrd"&gt;?&amp;gt;
&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;doc&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;
  &amp;lt;&lt;/span&gt;&lt;span class="html"&gt;assembly&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span class="html"&gt;name&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;MyTest&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;name&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;
  &amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;assembly&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;
  &amp;lt;&lt;/span&gt;&lt;span class="html"&gt;members&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span class="html"&gt;member&lt;/span&gt; &lt;span class="attr"&gt;name&lt;/span&gt;&lt;span class="kwrd"&gt;=&lt;/span&gt;&amp;quot;&lt;span class="kwrd"&gt;P:MyTest.MyClass.MyAttached&lt;/span&gt;&amp;quot;&lt;span class="kwrd"&gt;&amp;gt;
      &amp;lt;&lt;/span&gt;&lt;span class="html"&gt;summary&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;Summary for MyAttached attached property.&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;summary&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;
    &amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;member&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;
  &amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;members&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;
&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;doc&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;Add the XML comment file to the &lt;em&gt;Documentation Sources&lt;/em&gt; of your &lt;em&gt;SHFB&lt;/em&gt; project and the summary comments will appear in the attached property topic when the project is rebuilt. But what about linking back to the attached property topic from the dependency property field’s summary comment? Unfortunately the &lt;em&gt;C# &lt;/em&gt;compiler will warn about both of the following:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="remxml"&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;
&lt;span class="remxml"&gt;/// &lt;/span&gt;&lt;span class="rem"&gt;Identifies the &lt;/span&gt;&lt;span class="remxml"&gt;&amp;lt;see cref=&amp;quot;MyAttached&amp;quot; /&amp;gt;&lt;/span&gt;&lt;span class="rem"&gt; attached property.&lt;/span&gt;
&lt;span class="remxml"&gt;/// &lt;/span&gt;&lt;span class="remxml"&gt;&amp;lt;/summary&amp;gt;&lt;/span&gt;

&lt;span class="remxml"&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;
&lt;span class="remxml"&gt;/// &lt;/span&gt;&lt;span class="rem"&gt;Identifies the &lt;/span&gt;&lt;span class="remxml"&gt;&amp;lt;see cref=&amp;quot;MyTest.MyClass.MyAttached&amp;quot; /&amp;gt;&lt;/span&gt;&lt;span class="rem"&gt; attached property.&lt;/span&gt;
&lt;span class="remxml"&gt;/// &lt;/span&gt;&lt;span class="remxml"&gt;&amp;lt;/summary&amp;gt;&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;In both cases the compiler warns that it cannot find a member matching the member specified in the &lt;em&gt;see&lt;/em&gt; tag. This shouldn’t be that surprising because we already know there’s no physical property in the code. &lt;em&gt;Sandcastle&lt;/em&gt; will therefore be unable to provide a link and the resulting text will appear as bold.&amp;#160; Fortunately there is a way to provide a valid member reference for the attached property, in fact we’ve already done so in the separate XML comment file.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="remxml"&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;
&lt;span class="remxml"&gt;/// &lt;/span&gt;&lt;span class="rem"&gt;Identifies the &lt;/span&gt;&lt;span class="remxml"&gt;&amp;lt;see cref=&amp;quot;P:MyTest.MyClass.MyAttached&amp;quot; /&amp;gt;&lt;/span&gt;&lt;span class="rem"&gt; attached property.&lt;/span&gt;
&lt;span class="remxml"&gt;/// &lt;/span&gt;&lt;span class="remxml"&gt;&amp;lt;/summary&amp;gt;&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;Now the &lt;em&gt;C# &lt;/em&gt;compiler is happy and &lt;em&gt;Sandcastle&lt;/em&gt; can generate a link back to the attached property topic.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9201139154426574883-6336706366065317358?l=loadsofcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://loadsofcode.blogspot.com/feeds/6336706366065317358/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://loadsofcode.blogspot.com/2009/07/documenting-attached-properties-with.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/6336706366065317358'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/6336706366065317358'/><link rel='alternate' type='text/html' href='http://loadsofcode.blogspot.com/2009/07/documenting-attached-properties-with.html' title='Documenting Attached Properties with Sandcastle'/><author><name>Kevin Westhead</name><uri>http://www.blogger.com/profile/05226243485559749240</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/-T93lAVSpKrI/Tu__lq-Ia9I/AAAAAAAAAII/tnKoAeDFrrs/s220/Kevin%2BWesthead%2B%2528grey%2529.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9201139154426574883.post-510288615606752085</id><published>2009-07-14T23:00:00.000+01:00</published><updated>2009-07-14T23:33:08.271+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='C++'/><title type='text'>The Dispose Pattern in C++/CLI</title><content type='html'>&lt;p&gt;In my last post I talked about implementing events in &lt;em&gt;C++/CLI&lt;/em&gt;. I also briefly mentioned that the &lt;em&gt;C++/CLI&lt;/em&gt; team went to great lengths to correctly implement the dispose pattern as described in the &lt;a href="http://www.amazon.co.uk/gp/product/0321545613?ie=UTF8&amp;amp;tag=lo60co62-21&amp;amp;linkCode=as2&amp;amp;camp=1634&amp;amp;creative=6738&amp;amp;creativeASIN=0321545613"&gt;Framework Design Guidelines&lt;/a&gt;, using the familiar &lt;em&gt;C++&lt;/em&gt; &lt;a href="http://msdn.microsoft.com/en-us/library/ms177197.aspx"&gt;destructor syntax&lt;/a&gt;. This syntax is well documented so I won’t bother to go into detail about it, instead I’m going to focus on a quirk you’ll see when deriving from a class with a destructor. Here’s what you’ll see in a derived &lt;em&gt;C#&lt;/em&gt; class when overriding the &lt;em&gt;Dispose&lt;/em&gt; method.&lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;protected override void&lt;/span&gt; Dispose(&lt;span class="kwrd"&gt;bool&lt;/span&gt; __p1)
{
  &lt;span class="rem"&gt;// Dispose implementation omitted.&lt;/span&gt;
  &lt;span class="kwrd"&gt;base&lt;/span&gt;.Dispose(__p1);
}&lt;/pre&gt;

&lt;p&gt;Clearly someone thought a single underscore wasn’t enough &lt;font face="Wingdings"&gt;J&lt;/font&gt;. Somewhat surprisingly, there are no warnings generated for the &lt;em&gt;__p1&lt;/em&gt; parameter when code analysis is enabled, although I guess it explains how the parameter name slipped through in the first place. It could be that the code analysis tool knows the dispose pattern is being generated by the compiler and so ignores it completely, but I’m only speculating.&lt;/p&gt;

&lt;p&gt;So will they fix it in a future release? I think it’s unlikely. Why? Changing the parameter name would result in a breaking change when class libraries are recompiled with the new compiler. So is it likely users of languages with support for named parameters are referring to the &lt;em&gt;__p1&lt;/em&gt; parameter by name? Probably not but Microsoft’s track record on breaking changes is to avoid them unless they’re required to fix a security vulnerability, so I think this will remain as a quirk of &lt;em&gt;C++/CLI&lt;/em&gt;.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9201139154426574883-510288615606752085?l=loadsofcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://loadsofcode.blogspot.com/feeds/510288615606752085/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://loadsofcode.blogspot.com/2009/07/dispose-pattern-in-ccli.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/510288615606752085'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/510288615606752085'/><link rel='alternate' type='text/html' href='http://loadsofcode.blogspot.com/2009/07/dispose-pattern-in-ccli.html' title='The Dispose Pattern in C++/CLI'/><author><name>Kevin Westhead</name><uri>http://www.blogger.com/profile/05226243485559749240</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/-T93lAVSpKrI/Tu__lq-Ia9I/AAAAAAAAAII/tnKoAeDFrrs/s220/Kevin%2BWesthead%2B%2528grey%2529.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9201139154426574883.post-4908270268078633071</id><published>2009-07-10T23:00:00.000+01:00</published><updated>2009-07-10T23:56:36.990+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='C++'/><title type='text'>Implementing Events with C++/CLI</title><content type='html'>&lt;p&gt;I’ve been doing a fair amount of work in &lt;em&gt;C++&lt;/em&gt; recently, using &lt;em&gt;C++/CLI&lt;/em&gt; for interop between managed and unmanaged code. I found a minor problem when implementing events in a class library that I thought I’d share. As with &lt;em&gt;C#&lt;/em&gt; you have a couple of options for events: use the data member syntax or define individual event accessor methods. Just like &lt;em&gt;C#&lt;/em&gt; the former approach is nice and simple whereas the latter approach provides more flexibility. Unfortunately it’s the former approach that has the problem. Consider the following example:&lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public ref class&lt;/span&gt; MyClass
{
&lt;span class="kwrd"&gt;public&lt;/span&gt;:
  &lt;span class="kwrd"&gt;event&lt;/span&gt; System::EventHandler&amp;lt;MyEventArgs ^&amp;gt; ^MyEvent;
 
  &lt;span class="rem"&gt;// Remainder of MyClass omitted.&lt;/span&gt;
};&lt;/pre&gt;

&lt;p&gt;With this syntax the compiler will automatically produce the &lt;em&gt;add&lt;/em&gt;, &lt;em&gt;remove&lt;/em&gt; and &lt;em&gt;raise&lt;/em&gt; event accessor methods. The latter is protected so that derived classes can also raise the event, and this is where the problem occurs. There’s already a well defined pattern that class library authors should implement to allow derived classes to raise events defined in a base class. Unfortunately the data member event syntax in &lt;em&gt;C++/CLI&lt;/em&gt; doesn’t follow this pattern. The following &lt;em&gt;C#&lt;/em&gt; snippets show the recommended pattern and the equivalent of what the &lt;em&gt;C++/CLI&lt;/em&gt; compiler produces:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="rem"&gt;// Recommended method for raising MyEvent.&lt;/span&gt;
&lt;span class="kwrd"&gt;protected virtual void&lt;/span&gt; OnMyEvent(&lt;span class="type"&gt;MyEventArgs&lt;/span&gt; e)
{
  &lt;span class="rem"&gt;// Raise event.&lt;/span&gt;
}

&lt;span class="rem"&gt;// Method for raising MyEvent produced by C++/CLI compiler.&lt;/span&gt;
&lt;span class="kwrd"&gt;protected void&lt;/span&gt; raise_MyEvent(&lt;span class="kwrd"&gt;object&lt;/span&gt; sender, &lt;span class="type"&gt;MyEventArgs&lt;/span&gt; e)
{
  &lt;span class="rem"&gt;// Raise event.&lt;/span&gt;
}&lt;/pre&gt;

&lt;p&gt;The &lt;em&gt;C++/CLI&lt;/em&gt; compiler produces a method that, in addition to having an ugly name, only allows derived classes to raise the event. Derived classes cannot handle the event without attaching their own event handler . When you consider the lengths the &lt;em&gt;C++/CLI&lt;/em&gt; team went to implement the dispose pattern as described in the &lt;a href="http://www.amazon.co.uk/gp/product/0321545613?ie=UTF8&amp;amp;tag=lo60co62-21&amp;amp;linkCode=as2&amp;amp;camp=1634&amp;amp;creative=6738&amp;amp;creativeASIN=0321545613"&gt;Framework Design Guidelines&lt;/a&gt;, it’s surprising they didn’t provide the same support for events. Fortunately, although somewhat tediously if you have a large number of events, you can overcome this limitation by defining the individual event accessor methods as well as the correct virtual method for derived classes. You’ll also need to provide the backing field for the event.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public ref class&lt;/span&gt; MyClass
{
&lt;span class="kwrd"&gt;public&lt;/span&gt;:
  &lt;span class="kwrd"&gt;event&lt;/span&gt; System::EventHandler&amp;lt;MyEventArgs ^&amp;gt; ^MyEvent
  {
  &lt;span class="kwrd"&gt;public&lt;/span&gt;:
    &lt;span class="kwrd"&gt;void&lt;/span&gt; add(System::EventHandler&amp;lt;MyEventArgs ^&amp;gt; ^value);
    &lt;span class="kwrd"&gt;void&lt;/span&gt; remove(System::EventHandler&amp;lt;MyEventArgs ^&amp;gt; ^value);

  &lt;span class="kwrd"&gt;private&lt;/span&gt;:
    &lt;span class="kwrd"&gt;void&lt;/span&gt; raise(System::Object ^sender, MyEventArgs ^e);
  }
 
&lt;span class="kwrd"&gt;protected&lt;/span&gt;:
  &lt;span class="kwrd"&gt;virtual void&lt;/span&gt; OnMyEvent(MyEventArgs ^e);

&lt;span class="kwrd"&gt;private&lt;/span&gt;:
  System::EventHandler&amp;lt;MyEventArgs ^&amp;gt; ^m_myEvent;

  &lt;span class="rem"&gt;// Remainder of MyClass omitted.&lt;/span&gt;
};&lt;/pre&gt;

&lt;p&gt;It’s a shame you have to jump through these hoops to implement a pattern that has existed since the first version of the &lt;em&gt;.NET Framework&lt;/em&gt;. I also mentioned the lengths the &lt;em&gt;C++/CLI team &lt;/em&gt;went to implement the &lt;em&gt;dispose pattern &lt;/em&gt;earlier. Unfortunately this too has a problem, albeit a minor one, that I’ll talk about in the next post.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9201139154426574883-4908270268078633071?l=loadsofcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://loadsofcode.blogspot.com/feeds/4908270268078633071/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://loadsofcode.blogspot.com/2009/07/implementing-events-with-ccli.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/4908270268078633071'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/4908270268078633071'/><link rel='alternate' type='text/html' href='http://loadsofcode.blogspot.com/2009/07/implementing-events-with-ccli.html' title='Implementing Events with C++/CLI'/><author><name>Kevin Westhead</name><uri>http://www.blogger.com/profile/05226243485559749240</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/-T93lAVSpKrI/Tu__lq-Ia9I/AAAAAAAAAII/tnKoAeDFrrs/s220/Kevin%2BWesthead%2B%2528grey%2529.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9201139154426574883.post-301274426692294830</id><published>2009-02-19T23:00:00.000Z</published><updated>2009-02-19T23:57:06.702Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='Windows Forms'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><title type='text'>Restricting the Contents of Container Controls</title><content type='html'>&lt;p&gt;It’s quite common for container controls to place a restriction on the type of child controls they contain. For example, the &lt;a href="http://msdn.microsoft.com/en-gb/library/system.windows.forms.tabcontrol.aspx"&gt;TabControl&lt;/a&gt; class will only accept instances of the &lt;a href="http://msdn.microsoft.com/en-gb/library/system.windows.forms.tabpage.aspx"&gt;TabPage&lt;/a&gt; class as children. These controls will typically expose a type-safe collection to prevent users from adding the wrong type of child control. This is not a complete solution however, because it’s also possible to add child controls using the &lt;a href="http://msdn.microsoft.com/en-gb/library/system.windows.forms.control.controls.aspx"&gt;Controls&lt;/a&gt; property. In fact, this is exactly how the designer-generated initialisation code adds child controls. To prevent any bypassing of the child control restrictions you should override the &lt;a href="http://msdn.microsoft.com/en-gb/library/system.windows.forms.control.createcontrolsinstance.aspx"&gt;CreateControlsInstance&lt;/a&gt; method and return a more specialised control collection that provides the correct behaviour for adding and removing child controls. Consider the following example, where the &lt;em&gt;CustomPanel&lt;/em&gt; control is prohibited from having another &lt;em&gt;CustomPanel&lt;/em&gt; control as a child control.&lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public class&lt;/span&gt; &lt;span class="type"&gt;CustomPanel&lt;/span&gt; : &lt;span class="type"&gt;Panel&lt;/span&gt;
{
  &lt;span class="kwrd"&gt;protected override&lt;/span&gt; &lt;span class="type"&gt;Control&lt;/span&gt;.&lt;span class="type"&gt;ControlCollection&lt;/span&gt; CreateControlsInstance()
  {
    &lt;span class="kwrd"&gt;return new&lt;/span&gt; &lt;span class="type"&gt;CustomPanelControlCollection&lt;/span&gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt;);
  }

  &lt;span class="kwrd"&gt;private class&lt;/span&gt; &lt;span class="type"&gt;CustomPanelControlCollection&lt;/span&gt; : &lt;span class="type"&gt;Control&lt;/span&gt;.&lt;span class="type"&gt;ControlCollection&lt;/span&gt;
  {
    &lt;span class="kwrd"&gt;public&lt;/span&gt; CustomPanelControlCollection(&lt;span class="type"&gt;CustomPanel&lt;/span&gt; owner)
      : &lt;span class="kwrd"&gt;base&lt;/span&gt;(owner)
    {
    }

    &lt;span class="kwrd"&gt;public override void&lt;/span&gt; Add(&lt;span class="type"&gt;Control&lt;/span&gt; value)
    {
      &lt;span class="kwrd"&gt;if&lt;/span&gt; (value &lt;span class="kwrd"&gt;is&lt;/span&gt; &lt;span class="type"&gt;CustomPanel&lt;/span&gt;)
      {
        &lt;span class="kwrd"&gt;throw new&lt;/span&gt; &lt;span class="type"&gt;ArgumentException&lt;/span&gt;(
          &lt;span class="str"&gt;&amp;quot;Cannot add a CustomPanel control to another CustomPanel control.&amp;quot;&lt;/span&gt;, 
          &lt;span class="str"&gt;&amp;quot;control&amp;quot;&lt;/span&gt;);
      }
      &lt;span class="kwrd"&gt;base&lt;/span&gt;.Add(value);
    }

    &lt;span class="kwrd"&gt;public override void&lt;/span&gt; Remove(&lt;span class="type"&gt;Control&lt;/span&gt; value)
    {
      &lt;span class="kwrd"&gt;base&lt;/span&gt;.Remove(value);
      &lt;span class="kwrd"&gt;if&lt;/span&gt; (value &lt;span class="kwrd"&gt;is&lt;/span&gt; &lt;span class="type"&gt;CustomPanel&lt;/span&gt;)
      {
        &lt;span class="rem"&gt;// Additional remove code omitted.&lt;/span&gt;
      }
    }
  }

  &lt;span class="rem"&gt;// Remainder of CustomPanel omitted.&lt;/span&gt;
}&lt;/pre&gt;

&lt;p&gt;I’ve overridden the &lt;a href="http://msdn.microsoft.com/en-gb/library/system.windows.forms.control.controlcollection.remove.aspx"&gt;Remove&lt;/a&gt; method for completeness, but it can be omitted if there’s no need to perform any additional work when removing child controls from the collection. What about the other methods that can be used for adding and removing child controls? Well the &lt;a href="http://msdn.microsoft.com/en-gb/library/system.windows.forms.control.controlcollection.addrange.aspx"&gt;AddRange&lt;/a&gt; method and the implementation of the &lt;a href="http://msdn.microsoft.com/en-gb/library/system.collections.ilist.add.aspx"&gt;IList.Add&lt;/a&gt; method call the virtual &lt;a href="http://msdn.microsoft.com/en-gb/library/system.windows.forms.control.controlcollection.add.aspx"&gt;Add&lt;/a&gt; method. It’s not possible to add child controls at any position other than the end of the collection, so the implementation of the &lt;a href="http://msdn.microsoft.com/en-gb/library/system.collections.ilist.insert.aspx"&gt;IList.Insert&lt;/a&gt; method and the setter for the &lt;a href="http://msdn.microsoft.com/en-gb/library/system.collections.ilist.item.aspx"&gt;IList.Item&lt;/a&gt; property both throw &lt;a href="http://msdn.microsoft.com/en-gb/library/system.notsupportedexception.aspx"&gt;NotSupportedException&lt;/a&gt;. The &lt;a href="http://msdn.microsoft.com/en-gb/library/system.windows.forms.control.controlcollection.clear.aspx"&gt;Clear&lt;/a&gt;, &lt;a href="http://msdn.microsoft.com/en-gb/library/system.windows.forms.control.controlcollection.removeat.aspx"&gt;RemoveAt&lt;/a&gt;, &lt;a href="http://msdn.microsoft.com/en-gb/library/system.windows.forms.control.controlcollection.removebykey.aspx"&gt;RemoveByKey&lt;/a&gt; methods and the implementation of the &lt;a href="http://msdn.microsoft.com/en-gb/library/system.collections.ilist.remove.aspx"&gt;IList.Remove&lt;/a&gt; method all call the virtual &lt;em&gt;Remove&lt;/em&gt; method.&lt;/p&gt;

&lt;p&gt;This means we only need to override the &lt;em&gt;Add&lt;/em&gt; and &lt;em&gt;Remove&lt;/em&gt; methods as shown above, but it also highlights a weakness with the design of the &lt;a href="http://msdn.microsoft.com/en-gb/library/system.windows.forms.control.controlcollection.aspx"&gt;Control.ControlCollection&lt;/a&gt; class. When you have multiple virtual methods calling other virtual methods it can be difficult for inheritors to know which methods they should override. You’ll probably learn by unit testing the cases mentioned above or simply by using a tool such as &lt;a href="http://www.red-gate.com/products/reflector/index.htm"&gt;Reflector&lt;/a&gt;, but in both cases what you’re learning about is the implementation details of the &lt;em&gt;Control.ControlCollection&lt;/em&gt; class. It’s unfortunate when classes leak implementation details like this because it always leaves you with a problem. You can take the approach demonstrated above and hope that the &lt;em&gt;Windows Forms&lt;/em&gt; team doesn’t change the implementation in a way that breaks your collection. Alternatively you can override and seal the other virtual methods and re-implement any relevant explicitly implemented interface members to produce the desired call chain. Unfortunately preserving the contract of the overridden methods can be more difficult than it first seems, especially if the base class implementations have access to members that are not accessible from derived classes. I think the former approach is the lesser of two evils based on the trend for minimising breaking changes in the &lt;em&gt;.NET Framework&lt;/em&gt;, but YMMV.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9201139154426574883-301274426692294830?l=loadsofcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://loadsofcode.blogspot.com/feeds/301274426692294830/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://loadsofcode.blogspot.com/2009/02/restricting-contents-of-container.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/301274426692294830'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/301274426692294830'/><link rel='alternate' type='text/html' href='http://loadsofcode.blogspot.com/2009/02/restricting-contents-of-container.html' title='Restricting the Contents of Container Controls'/><author><name>Kevin Westhead</name><uri>http://www.blogger.com/profile/05226243485559749240</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/-T93lAVSpKrI/Tu__lq-Ia9I/AAAAAAAAAII/tnKoAeDFrrs/s220/Kevin%2BWesthead%2B%2528grey%2529.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9201139154426574883.post-5056782651385935111</id><published>2009-02-18T23:00:00.000Z</published><updated>2009-02-19T00:27:44.800Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='Windows Forms'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><title type='text'>Declaring Default Values for Control Properties</title><content type='html'>&lt;p&gt;Default values for properties must be documented to make users aware of a control’s default state. This information is also useful for visual designers and code generators. A visual designer can use the default value to perform a “reset” in the property grid, and a code generator can use the default value to determine whether or not it should persist the property in designer-generated initialisation code.&lt;/p&gt;  &lt;p&gt;Consider the following example, where the &lt;em&gt;CustomListView&lt;/em&gt; control exposes a hover delay for generating a hover event during a drag-and-drop operation.&lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public class&lt;/span&gt; &lt;span class="type"&gt;CustomListView&lt;/span&gt; : &lt;span class="type"&gt;ListView&lt;/span&gt;
{
  &lt;span class="kwrd"&gt;private int&lt;/span&gt; m_dragHoverTime = 400;

  &lt;span class="kwrd"&gt;public int&lt;/span&gt; DragHoverTime
  {
    &lt;span class="kwrd"&gt;get&lt;/span&gt; { &lt;span class="kwrd"&gt;return&lt;/span&gt; m_dragHoverTime; }
    &lt;span class="kwrd"&gt;set&lt;/span&gt; { m_dragHoverTime = &lt;span class="kwrd"&gt;value&lt;/span&gt;; }
  }

  &lt;span class="rem"&gt;// Remainder of CustomListView omitted.&lt;/span&gt;
}&lt;/pre&gt;

&lt;p&gt;The default value of 400 milliseconds can be documented but a visual designer will not be aware of this value. This results in the property being displayed in bold in the &lt;em&gt;Visual Studio&lt;/em&gt; property grid, which indicates a non-default value. The value is also persisted in the designer-generated initialisation code. Use the &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx"&gt;DefaultValueAttribute&lt;/a&gt; class to advertise the default value of a property to visual designers and code generators.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public class&lt;/span&gt; &lt;span class="type"&gt;CustomListView&lt;/span&gt; : &lt;span class="type"&gt;ListView&lt;/span&gt;
{
  &lt;span class="kwrd"&gt;private const int&lt;/span&gt; DefaultDragHoverTime = 400;
  &lt;span class="kwrd"&gt;private int&lt;/span&gt; m_dragHoverTime = DefaultDragHoverTime;

  [&lt;span class="type"&gt;DefaultValue&lt;/span&gt;(DefaultDragHoverTime)]
  &lt;span class="kwrd"&gt;public int&lt;/span&gt; DragHoverTime
  {
    &lt;span class="kwrd"&gt;get&lt;/span&gt; { &lt;span class="kwrd"&gt;return&lt;/span&gt; m_dragHoverTime; }
    &lt;span class="kwrd"&gt;set&lt;/span&gt; { m_dragHoverTime = &lt;span class="kwrd"&gt;value&lt;/span&gt;; }
  }

  &lt;span class="rem"&gt;// Remainder of CustomListView omitted.&lt;/span&gt;
}&lt;/pre&gt;

&lt;p&gt;With this approach the control’s hover delay time is only persisted in designer-generated initialisation code if it is different from the default value. Similarly, a visual designer will display the value correctly in the property grid and will also be able to perform a reset back to the default value. It’s worth noting that there’s a system-defined hover delay value returned by the &lt;a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.systeminformation.mousehovertime.aspx"&gt;SystemInformation.MouseHoverTime&lt;/a&gt; property. This seems like a better candidate for a default value than the previous 400 millisecond value. Unfortunately, it’s not possible to use this value with the &lt;em&gt;DefaultValueAttribute&lt;/em&gt; class but there is another option – the &lt;a href="http://msdn.microsoft.com/en-us/library/53b8022e.aspx"&gt;ShouldSerialize and Reset methods&lt;/a&gt; pattern.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public class&lt;/span&gt; &lt;span class="type"&gt;CustomListView&lt;/span&gt; : &lt;span class="type"&gt;ListView&lt;/span&gt;
{
  &lt;span class="kwrd"&gt;private int&lt;/span&gt; m_dragHoverTime = &lt;span class="type"&gt;SystemInformation&lt;/span&gt;.MouseHoverTime;

  &lt;span class="kwrd"&gt;public int&lt;/span&gt; DragHoverTime
  {
    &lt;span class="kwrd"&gt;get&lt;/span&gt; { &lt;span class="kwrd"&gt;return&lt;/span&gt; m_dragHoverTime; }
    &lt;span class="kwrd"&gt;set&lt;/span&gt; { m_dragHoverTime = &lt;span class="kwrd"&gt;value&lt;/span&gt;; }
  }

  &lt;span class="kwrd"&gt;private bool&lt;/span&gt; ShouldSerializeDragHoverTime()
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; DragHoverTime != &lt;span class="type"&gt;SystemInformation&lt;/span&gt;.MouseHoverTime;
  }

  &lt;span class="kwrd"&gt;private void&lt;/span&gt; ResetDragHoverTime()
  {
    DragHoverTime = &lt;span class="type"&gt;SystemInformation&lt;/span&gt;.MouseHoverTime;
  }

  &lt;span class="rem"&gt;// Remainder of CustomListView omitted.&lt;/span&gt;
}&lt;/pre&gt;

&lt;p&gt;This still isn’t ideal because the value returned by &lt;em&gt;SystemInformation.MouseHoverTime&lt;/em&gt; reflects a system-wide parameter that can vary across machines. This could result in unpredictable behaviour when using visual designers in a team environment. For example, resetting to the default value on one developer’s machine could result in another developer seeing a non-default value on their machine. Even so, it seems wrong not to provide developers with the facility to use the system-defined value. At this point you might be asking “Why not always used the system-defined value?” That’s definitely a sensible strategy, in which case you don’t even need to expose the &lt;em&gt;DragHoverTime&lt;/em&gt; property. But we haven’t come this far just to ditch the property &lt;font face="Wingdings"&gt;J&lt;/font&gt;. The actual scenario where I’ve used something similar to this example before involved using the system-defined value in all but one place. The exception was where usability feedback demonstrated that the system-defined value wasn’t long enough for the desired user interaction. The solution was to provide a &lt;em&gt;UseSystemMouseHoverTime&lt;/em&gt; property to indicate whether or not the control should use the system-defined value or its own value, which means we can go back to the &lt;em&gt;DefaultValueAttribute&lt;/em&gt; class after all &lt;font face="Wingdings"&gt;J&lt;/font&gt;.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public class&lt;/span&gt; &lt;span class="type"&gt;CustomListView&lt;/span&gt; : &lt;span class="type"&gt;ListView&lt;/span&gt;
{
  &lt;span class="kwrd"&gt;private const int&lt;/span&gt; DefaultDragHoverTime = 400;
  &lt;span class="kwrd"&gt;private int&lt;/span&gt; m_dragHoverTime = DefaultDragHoverTime;
  &lt;span class="kwrd"&gt;private bool&lt;/span&gt; m_useSystemMouseHoverTime = &lt;span class="kwrd"&gt;true&lt;/span&gt;;

  [&lt;span class="type"&gt;DefaultValue&lt;/span&gt;(DefaultDragHoverTime)]
  &lt;span class="kwrd"&gt;public int&lt;/span&gt; DragHoverTime
  {
    &lt;span class="kwrd"&gt;get&lt;/span&gt; { &lt;span class="kwrd"&gt;return&lt;/span&gt; m_dragHoverTime; }
    &lt;span class="kwrd"&gt;set&lt;/span&gt; { m_dragHoverTime = &lt;span class="kwrd"&gt;value&lt;/span&gt;; }
  }

  [&lt;span class="type"&gt;DefaultValue&lt;/span&gt;(&lt;span class="kwrd"&gt;true&lt;/span&gt;)]
  &lt;span class="kwrd"&gt;public bool&lt;/span&gt; UseSystemMouseHoverTime
  {
    &lt;span class="kwrd"&gt;get&lt;/span&gt; { &lt;span class="kwrd"&gt;return&lt;/span&gt; m_useSystemMouseHoverTime; }
    &lt;span class="kwrd"&gt;set&lt;/span&gt; { m_useSystemMouseHoverTime = &lt;span class="kwrd"&gt;value&lt;/span&gt;; }
  }

  &lt;span class="rem"&gt;// Remainder of CustomListView omitted.&lt;/span&gt;
}&lt;/pre&gt;

&lt;p&gt;Obviously that’s a very specific scenario, but the key thing to remember is that you should make sure your controls have sensible defaults and that those defaults are properly reflected in a designer.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9201139154426574883-5056782651385935111?l=loadsofcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://loadsofcode.blogspot.com/feeds/5056782651385935111/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://loadsofcode.blogspot.com/2009/02/declaring-default-values-for-control.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/5056782651385935111'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/5056782651385935111'/><link rel='alternate' type='text/html' href='http://loadsofcode.blogspot.com/2009/02/declaring-default-values-for-control.html' title='Declaring Default Values for Control Properties'/><author><name>Kevin Westhead</name><uri>http://www.blogger.com/profile/05226243485559749240</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/-T93lAVSpKrI/Tu__lq-Ia9I/AAAAAAAAAII/tnKoAeDFrrs/s220/Kevin%2BWesthead%2B%2528grey%2529.jpg'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9201139154426574883.post-7367931254221578218</id><published>2009-02-13T23:00:00.000Z</published><updated>2009-02-13T23:28:05.164Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='Windows Forms'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><title type='text'>Hiding Base Class Members in Controls</title><content type='html'>&lt;p&gt;Even when you &lt;a href="http://blogs.msdn.com/jfoscoding/archive/2004/12/03/274186.aspx"&gt;pick your base class wisely&lt;/a&gt;, it’s entirely possible for the base class to contain properties and/or events that are not meaningful for your custom control. Having these members available at design-time via a visual designer’s property grid or a code editor’s &lt;em&gt;IntelliSense&lt;/em&gt; makes it harder for API users to spot the genuinely useful members. Consider the &lt;em&gt;CustomPanel&lt;/em&gt; control below, where the size and enabled state are determined by the control’s parent. There’s no point advertising the &lt;a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.panel.autosize.aspx"&gt;AutoSize&lt;/a&gt; and &lt;a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.control.enabled.aspx"&gt;Enabled&lt;/a&gt; properties for this control, so we should hide them.&lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public class&lt;/span&gt; &lt;span class="type"&gt;CustomPanel&lt;/span&gt; : &lt;span class="type"&gt;Panel&lt;/span&gt;
{
  [&lt;span class="type"&gt;Browsable&lt;/span&gt;(&lt;span class="kwrd"&gt;false&lt;/span&gt;)]
  [&lt;span class="type"&gt;DesignerSerializationVisibility&lt;/span&gt;(&lt;span class="type"&gt;DesignerSerializationVisibility&lt;/span&gt;.Hidden)]
  [&lt;span class="type"&gt;EditorBrowsable&lt;/span&gt;(&lt;span class="type"&gt;EditorBrowsableState&lt;/span&gt;.Never)]
  &lt;span class="kwrd"&gt;public override bool&lt;/span&gt; AutoSize
  {
    &lt;span class="kwrd"&gt;get&lt;/span&gt; { &lt;span class="kwrd"&gt;return base&lt;/span&gt;.AutoSize; }
    &lt;span class="kwrd"&gt;set&lt;/span&gt; { &lt;span class="kwrd"&gt;base&lt;/span&gt;.AutoSize = &lt;span class="kwrd"&gt;value&lt;/span&gt;; }
  }

  [&lt;span class="type"&gt;Browsable&lt;/span&gt;(&lt;span class="kwrd"&gt;false&lt;/span&gt;)]
  [&lt;span class="type"&gt;DesignerSerializationVisibility&lt;/span&gt;(&lt;span class="type"&gt;DesignerSerializationVisibility&lt;/span&gt;.Hidden)]
  [&lt;span class="type"&gt;EditorBrowsable&lt;/span&gt;(&lt;span class="type"&gt;EditorBrowsableState&lt;/span&gt;.Never)]
  &lt;span class="kwrd"&gt;public new bool&lt;/span&gt; Enabled
  {
    &lt;span class="kwrd"&gt;get&lt;/span&gt; { &lt;span class="kwrd"&gt;return base&lt;/span&gt;.Enabled; }
    &lt;span class="kwrd"&gt;set&lt;/span&gt; { &lt;span class="kwrd"&gt;base&lt;/span&gt;.Enabled = &lt;span class="kwrd"&gt;value&lt;/span&gt;; }
  }

  &lt;span class="rem"&gt;// Remainder of CustomPanel omitted.&lt;/span&gt;
}&lt;/pre&gt;

&lt;p&gt;The following attributes have been used to hide the properties at design-time.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;The &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.browsableattribute.aspx"&gt;BrowsableAttribute&lt;/a&gt; class is used to hide the properties from a visual designer’s property grid. &lt;/li&gt;

  &lt;li&gt;The &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.designerserializationvisibilityattribute.aspx"&gt;DesignerSerializationVisibilityAttribute&lt;/a&gt; class is used to prevent the property from being persisted in designer-generated initialisation code. &lt;/li&gt;

  &lt;li&gt;The &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.editorbrowsableattribute.aspx"&gt;EditorBrowsableAttribute&lt;/a&gt; class is used to prevent the property from appearing in the code editor’s &lt;em&gt;IntelliSense&lt;/em&gt;. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Defining the attributes on the &lt;em&gt;AutoSize&lt;/em&gt; property is straightforward since it is virtual and can be overridden. The &lt;em&gt;Enabled&lt;/em&gt; property is non-virtual so we cannot define the attributes on this property and must instead create another &lt;em&gt;Enabled&lt;/em&gt; property to hide the inherited one. In both cases the original contract is preserved by calling through to the base class members.&lt;/p&gt;

&lt;p&gt;When hiding members it is also important to consider any related members such as events. In the above example, we must consider the property changed events for &lt;em&gt;AutoSize&lt;/em&gt; and &lt;em&gt;Enabled&lt;/em&gt; properties, which will still be visible at design-time. The same techniques used for both properties are also applicable to their events as shown below.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public class&lt;/span&gt; &lt;span class="type"&gt;CustomPanel&lt;/span&gt; : &lt;span class="type"&gt;Panel&lt;/span&gt;
{
  [&lt;span class="type"&gt;Browsable&lt;/span&gt;(&lt;span class="kwrd"&gt;false&lt;/span&gt;)]
  [&lt;span class="type"&gt;EditorBrowsable&lt;/span&gt;(&lt;span class="type"&gt;EditorBrowsableState&lt;/span&gt;.Never)]
  &lt;span class="kwrd"&gt;public new event&lt;/span&gt; &lt;span class="type"&gt;EventHandler&lt;/span&gt; AutoSizeChanged
  {
    &lt;span class="kwrd"&gt;add&lt;/span&gt; { &lt;span class="kwrd"&gt;base&lt;/span&gt;.AutoSizeChanged += &lt;span class="kwrd"&gt;value&lt;/span&gt;; }
    &lt;span class="kwrd"&gt;remove&lt;/span&gt; { &lt;span class="kwrd"&gt;base&lt;/span&gt;.AutoSizeChanged -= &lt;span class="kwrd"&gt;value&lt;/span&gt;; }
  }

  [&lt;span class="type"&gt;Browsable&lt;/span&gt;(&lt;span class="kwrd"&gt;false&lt;/span&gt;)]
  [&lt;span class="type"&gt;EditorBrowsable&lt;/span&gt;(&lt;span class="type"&gt;EditorBrowsableState&lt;/span&gt;.Never)]
  &lt;span class="kwrd"&gt;public new event&lt;/span&gt; &lt;span class="type"&gt;EventHandler&lt;/span&gt; EnabledChanged
  {
    &lt;span class="kwrd"&gt;add&lt;/span&gt; { &lt;span class="kwrd"&gt;base&lt;/span&gt;.EnabledChanged += &lt;span class="kwrd"&gt;value&lt;/span&gt;; }
    &lt;span class="kwrd"&gt;remove&lt;/span&gt; { &lt;span class="kwrd"&gt;base&lt;/span&gt;.EnabledChanged -= &lt;span class="kwrd"&gt;value&lt;/span&gt;; }
  }

  &lt;span class="rem"&gt;// Remainder of CustomPanel omitted.&lt;/span&gt;
}&lt;/pre&gt;

&lt;p&gt;&lt;em&gt;Windows Forms&lt;/em&gt; controls should follow the event pattern described in the &lt;a href="http://www.amazon.co.uk/gp/product/0321545613?ie=UTF8&amp;amp;tag=lo60co62-21&amp;amp;linkCode=as2&amp;amp;camp=1634&amp;amp;creative=6738&amp;amp;creativeASIN=0321545613"&gt;Framework&amp;#160; Design Guidelines&lt;/a&gt; and raise their events from protected virtual methods. You should consider hiding these methods as well but in practice, hiding these members is unnecessary since it will still be useful for derived controls to interact with these events even when they’ve been hidden from the designer/code editor.&lt;/p&gt;

&lt;p&gt;It is important to reiterate that the motivation for hiding base class members is to prevent meaningless members from appearing at design-time. It is not the intention to enforce runtime restrictions because we should always preserve the contract of the base class members. This is why neither property setter throws an exception.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9201139154426574883-7367931254221578218?l=loadsofcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://loadsofcode.blogspot.com/feeds/7367931254221578218/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://loadsofcode.blogspot.com/2009/02/hiding-base-class-members-in-controls.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/7367931254221578218'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/7367931254221578218'/><link rel='alternate' type='text/html' href='http://loadsofcode.blogspot.com/2009/02/hiding-base-class-members-in-controls.html' title='Hiding Base Class Members in Controls'/><author><name>Kevin Westhead</name><uri>http://www.blogger.com/profile/05226243485559749240</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/-T93lAVSpKrI/Tu__lq-Ia9I/AAAAAAAAAII/tnKoAeDFrrs/s220/Kevin%2BWesthead%2B%2528grey%2529.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9201139154426574883.post-762513824989882988</id><published>2009-02-12T23:00:00.001Z</published><updated>2009-02-13T04:15:23.380Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='WPF'/><category scheme='http://www.blogger.com/atom/ns#' term='Windows Forms'/><category scheme='http://www.blogger.com/atom/ns#' term='Implementing Observable Objects'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><title type='text'>Implementing Observable Objects – Part VI</title><content type='html'>&lt;p&gt;In &lt;a href="http://loadsofcode.blogspot.com/2009/02/implementing-observable-objects-part-v.html"&gt;Part V&lt;/a&gt; I mentioned that the &lt;em&gt;ObservableItem&lt;/em&gt; class makes no checks to ensure any UI updates are made on the correct thread, which means it could potentially violate the threading model employed by both &lt;em&gt;Windows Forms&lt;/em&gt; and &lt;em&gt;WPF&lt;/em&gt;. Now if you spent much time working with &lt;em&gt;WPF&lt;/em&gt; you’re probably aware that the data binding mechanism can actually cope with &lt;a href="http://msdn.microsoft.com/en-gb/library/system.componentmodel.inotifypropertychanged.propertychanged.aspx"&gt;PropertyChanged&lt;/a&gt; events raised on different threads to the bound UI object. &lt;em&gt;Windows Forms&lt;/em&gt; on the other hand will dutifully throw an &lt;a href="http://msdn.microsoft.com/en-gb/library/system.invalidoperationexception.aspx"&gt;InvalidOperationException&lt;/a&gt; in the same scenario if the &lt;a href="http://msdn.microsoft.com/en-gb/library/system.windows.forms.control.checkforillegalcrossthreadcalls.aspx"&gt;CheckForIllegalCrossThreadCalls&lt;/a&gt; property is set to true. So if you only want to target &lt;em&gt;WPF&lt;/em&gt; then you can get away with doing nothing, but I wouldn’t recommend this approach. Firstly, if you later discovered you needed to use the same data model with &lt;em&gt;Windows Forms&lt;/em&gt; you might find it to be a non-trivial change, especially if other &lt;em&gt;WPF&lt;/em&gt; dependencies have crept in. I know this appears to violate the &lt;a href="http://en.wikipedia.org/wiki/YAGNI"&gt;YAGNI&lt;/a&gt; approach but we’re not really talking about adding unnecessary functionality, we’re trying not to unnecessarily prohibit reuse of the data model. Secondly, dealing with concurrency is hard enough without letting it ambush you &lt;font face="Wingdings"&gt;J&lt;/font&gt;. I’m not saying you should never perform data model operations on a background thread, but you should always ensure that any resulting UI updates are marshalled to the correct thread. We can ensure we’re on the correct thread by making the following modifications to the &lt;em&gt;ObservableItem&lt;/em&gt; class:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;private readonly&lt;/span&gt; &lt;span class="type"&gt;Thread&lt;/span&gt; m_synchronizationThread = &lt;span class="type"&gt;Thread&lt;/span&gt;.CurrentThread;
&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="type"&gt;PropertyChangedEventHandler&lt;/span&gt; m_propertyChangedEventHandler;

&lt;span class="kwrd"&gt;public event&lt;/span&gt; &lt;span class="type"&gt;PropertyChangedEventHandler&lt;/span&gt; PropertyChanged
{
  &lt;span class="kwrd"&gt;add&lt;/span&gt;
  {
    VerifySynchronizationThread();
    m_propertyChangedEventHandler += &lt;span class="kwrd"&gt;value&lt;/span&gt;;
  }
  &lt;span class="kwrd"&gt;remove&lt;/span&gt;
  {
    VerifySynchronizationThread();
    m_propertyChangedEventHandler -= &lt;span class="kwrd"&gt;value&lt;/span&gt;;
  }
}

[&lt;span class="type"&gt;MethodImpl&lt;/span&gt;(&lt;span class="type"&gt;MethodImplOptions&lt;/span&gt;.NoInlining)]
&lt;span class="kwrd"&gt;private void&lt;/span&gt; SetPropertyInternal&amp;lt;T&amp;gt;(
  &lt;span class="kwrd"&gt;string&lt;/span&gt; propertyName, &lt;span class="kwrd"&gt;ref&lt;/span&gt; T field, T value, &lt;span class="type"&gt;IEqualityComparer&lt;/span&gt;&amp;lt;T&amp;gt; comparer)
{
  &lt;span class="kwrd"&gt;if&lt;/span&gt; (VerifySetPropertyArguments)
  {
    VerifySetPropertyInternalArguments(propertyName, comparer);
  }
  VerifySynchronizationThread();
  &lt;span class="kwrd"&gt;if&lt;/span&gt; (!comparer.Equals(field, value))
  {
    T oldValue = field;
    field = value;
    &lt;span class="kwrd"&gt;try&lt;/span&gt;
    {
      OnPropertyChanged(&lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="type"&gt;PropertyChangedEventArgs&lt;/span&gt;(propertyName));
    }
    &lt;span class="kwrd"&gt;catch&lt;/span&gt;
    {
      field = oldValue;
      &lt;span class="kwrd"&gt;throw&lt;/span&gt;;
    }
  }
}

&lt;span class="kwrd"&gt;private void&lt;/span&gt; VerifySynchronizationThread()
{
  &lt;span class="kwrd"&gt;if&lt;/span&gt; (m_synchronizationThread != &lt;span class="type"&gt;Thread&lt;/span&gt;.CurrentThread)
  {
    &lt;span class="kwrd"&gt;throw new&lt;/span&gt; &lt;span class="type"&gt;InvalidOperationException&lt;/span&gt;(
      &lt;span class="str"&gt;&amp;quot;The current object is being updated on a thread that is different from the &amp;quot;&lt;/span&gt; + 
      &lt;span class="str"&gt;&amp;quot;thread it was created on.&amp;quot;&lt;/span&gt;);
  }
}&lt;/pre&gt;

&lt;p&gt;Now whenever the &lt;em&gt;SetPropertyInternal&lt;/em&gt; method is called or an event handler is registered or unregistered for the &lt;em&gt;PropertyChanged&lt;/em&gt; event, the &lt;em&gt;VerifySynchronizationThread&lt;/em&gt; method is called to ensure we’re on the correct thread. This protects us from unintentional UI updates on another thread, but what about when we need a data model object to perform a potentially long running operation on a background thread? Clearly we don’t want to be calling methods such as &lt;a href="http://msdn.microsoft.com/en-gb/library/system.windows.forms.control.invoke.aspx"&gt;Control.Invoke&lt;/a&gt; or &lt;a href="http://msdn.microsoft.com/en-gb/library/system.windows.threading.dispatcher.invoke.aspx"&gt;Dispatcher.Invoke&lt;/a&gt; from data model objects because that would tie us to either &lt;em&gt;Windows Forms&lt;/em&gt; or &lt;em&gt;WPF&lt;/em&gt;. This is where the &lt;a href="http://msdn.microsoft.com/en-gb/library/system.threading.synchronizationcontext.aspx"&gt;SynchronizationContext&lt;/a&gt; class comes in, which allows us to &lt;a href="http://msdn.microsoft.com/en-gb/library/system.threading.synchronizationcontext.send.aspx"&gt;Send&lt;/a&gt; (synchronous) or &lt;a href="http://msdn.microsoft.com/en-gb/library/system.threading.synchronizationcontext.post.aspx"&gt;Post&lt;/a&gt; (asynchronous) updates to the UI correctly. Consider the following addition to the &lt;em&gt;Person&lt;/em&gt; class:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public void&lt;/span&gt; LongRunningOperation()
{
  &lt;span class="kwrd"&gt;var&lt;/span&gt; currentContext = &lt;span class="type"&gt;SynchronizationContext&lt;/span&gt;.Current;
  &lt;span class="kwrd"&gt;if&lt;/span&gt; (currentContext == &lt;span class="kwrd"&gt;null&lt;/span&gt;)
  {
    currentContext = &lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="type"&gt;SynchronizationContext&lt;/span&gt;();
  }
  &lt;span class="type"&gt;ThreadPool&lt;/span&gt;.QueueUserWorkItem(
    &lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="type"&gt;WaitCallback&lt;/span&gt;(
      state1 =&amp;gt;
      {
        &lt;span class="kwrd"&gt;string&lt;/span&gt; processedFirstName = GetUpperLowerString(FirstName);
        &lt;span class="kwrd"&gt;string&lt;/span&gt; processedLastName = GetUpperLowerString(LastName);
        currentContext.Post(
          &lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="type"&gt;SendOrPostCallback&lt;/span&gt;(
            state2 =&amp;gt;
            {
              FirstName = processedFirstName;
              LastName = processedLastName;
            }), 
          &lt;span class="kwrd"&gt;null&lt;/span&gt;);
      }));
}

&lt;span class="kwrd"&gt;private static string&lt;/span&gt; GetUpperLowerString(&lt;span class="kwrd"&gt;string&lt;/span&gt; value)
{
  &lt;span class="kwrd"&gt;var&lt;/span&gt; result = &lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="type"&gt;StringBuilder&lt;/span&gt;(value.Length);
  &lt;span class="kwrd"&gt;for&lt;/span&gt; (&lt;span class="kwrd"&gt;int&lt;/span&gt; i = 0; i &amp;lt; value.Length; ++i)
  {
    &lt;span class="kwrd"&gt;string&lt;/span&gt; textElement = &lt;span class="type"&gt;StringInfo&lt;/span&gt;.GetNextTextElement(value, i);
    result.Append((i % 2) == 0 ? 
      textElement.ToUpperInvariant() : 
      textElement.ToLowerInvariant());
  }
  &lt;span class="kwrd"&gt;return&lt;/span&gt; result.ToString();
}&lt;/pre&gt;

&lt;p&gt;Now I’ve cheated a little here since my “long running” operation does nothing more than alternate the case of characters in the &lt;em&gt;FirstName&lt;/em&gt; and &lt;em&gt;LastName&lt;/em&gt; properties &lt;font face="Wingdings"&gt;J&lt;/font&gt;. We use the &lt;a href="http://msdn.microsoft.com/en-gb/library/system.threading.synchronizationcontext.current.aspx"&gt;SynchronizationContext.Current&lt;/a&gt; property to return a &lt;em&gt;SynchronizationContext&lt;/em&gt; object that will update the &lt;em&gt;FirstName&lt;/em&gt; and &lt;em&gt;LastName&lt;/em&gt; properties, and therefore any data bound view, on the correct thread. If the property returns null then we use a default &lt;em&gt;SynchronizationContext&lt;/em&gt;. We do this because if the default &lt;em&gt;SynchronizationContext&lt;/em&gt; doesn’t do the correct thing, which is likely, then the resulting &lt;em&gt;InvalidOperationException&lt;/em&gt; will be more helpful than a &lt;a href="http://msdn.microsoft.com/en-gb/library/system.nullreferenceexception.aspx"&gt;NullReferenceException&lt;/a&gt;. I’ve added a button to both sample applications so that you can test this exciting functionality out &lt;font face="Wingdings"&gt;J&lt;/font&gt;.&lt;/p&gt;

&lt;p&gt;Now you might be wondering why we don’t store the current &lt;em&gt;SynchronizationContext&lt;/em&gt; instead of the current thread. Unfortunately we’re unlikely to get the same instance back in a &lt;em&gt;WPF&lt;/em&gt; application due to the way &lt;em&gt;WPF&lt;/em&gt; sets the current &lt;em&gt;SynchronizationContext&lt;/em&gt; and because none of the derived classes override the &lt;a href="http://msdn.microsoft.com/en-gb/library/bsc2ak47.aspx"&gt;Equals&lt;/a&gt; method, reference equality is all we can use.&lt;/p&gt;

&lt;p&gt;Well I think that’s enough on this topic, at least for a little while &lt;font face="Wingdings"&gt;J&lt;/font&gt;. I promise the next post will be about something different.&lt;/p&gt;
&lt;iframe style="border-right: #dde5e9 1px solid; padding-right: 0px; border-top: #dde5e9 1px solid; padding-left: 0px; padding-bottom: 0px; margin: 3px; border-left: #dde5e9 1px solid; width: 240px; padding-top: 0px; border-bottom: #dde5e9 1px solid; height: 66px; background-color: #ffffff" marginwidth="0" marginheight="0" src="http://cid-4fea45d461294bd0.skydrive.live.com/embedrowdetail.aspx/Public/LoadsOfCode/Implementing%20Observable%20Objects%20-%20Part%20VI.zip" frameborder="0" scrolling="no"&gt;&lt;/iframe&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9201139154426574883-762513824989882988?l=loadsofcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://loadsofcode.blogspot.com/feeds/762513824989882988/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://loadsofcode.blogspot.com/2009/02/implementing-observable-objects-part-vi.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/762513824989882988'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/762513824989882988'/><link rel='alternate' type='text/html' href='http://loadsofcode.blogspot.com/2009/02/implementing-observable-objects-part-vi.html' title='Implementing Observable Objects – Part VI'/><author><name>Kevin Westhead</name><uri>http://www.blogger.com/profile/05226243485559749240</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/-T93lAVSpKrI/Tu__lq-Ia9I/AAAAAAAAAII/tnKoAeDFrrs/s220/Kevin%2BWesthead%2B%2528grey%2529.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9201139154426574883.post-2560828741736952274</id><published>2009-02-06T23:00:00.001Z</published><updated>2009-02-13T04:13:53.278Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='WPF'/><category scheme='http://www.blogger.com/atom/ns#' term='Windows Forms'/><category scheme='http://www.blogger.com/atom/ns#' term='Implementing Observable Objects'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><title type='text'>Implementing Observable Objects – Part V</title><content type='html'>&lt;p&gt;In &lt;a href="http://loadsofcode.blogspot.com/2009/02/implementing-observable-objects-part-iv.html"&gt;Part IV&lt;/a&gt; I mentioned that the &lt;em&gt;SetPropertyInternal&lt;/em&gt; method can call unknown code. This is true for any method that raises an event. Why is this a problem? It’s a problem for the &lt;em&gt;SetPropertyInternal&lt;/em&gt; method because we raise the event after changing the property’s value. This makes sense because event handlers will want to know what the new value of the property is. If an event handler throws an exception however, we’re left in a state where a property has been changed as part of an operation that did not complete successfully. So how should we deal with this? We should provide one of three established guarantees in the face of errors:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;The &lt;strong&gt;basic&lt;/strong&gt; guarantee – data and invariants remain valid when the operation fails. &lt;/li&gt;
  &lt;li&gt;The &lt;strong&gt;strong&lt;/strong&gt; guarantee – data is rolled back to its original state when the operation fails. &lt;/li&gt;
  &lt;li&gt;The &lt;strong&gt;no-fail&lt;/strong&gt; guarantee – the operation cannot fail. &lt;/li&gt; &lt;/ul&gt;

&lt;p&gt;Anything less than the basic guarantee has to be treated as a bug that must be fixed. The &lt;em&gt;ObservableItem&lt;/em&gt; class currently honours the basic guarantee, i.e. the data remains valid for the object because it was an event handler that failed rather than the property’s own validation logic. So we don’t need to do anything, right? Well we should always strive to provide the strongest guarantee possible, unless providing a guarantee stronger than the basic guarantee unreasonably punishes callers for the majority of usage scenarios. Providing the no-fail guarantee is not possible here because we have no control over the event handlers. Can we provide the strong guarantee? Yes, by changing the &lt;em&gt;SetPropertyInternal&lt;/em&gt; implementation as shown below:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;private void&lt;/span&gt; SetPropertyInternal&amp;lt;T&amp;gt;(
  &lt;span class="kwrd"&gt;string&lt;/span&gt; propertyName, &lt;span class="kwrd"&gt;ref&lt;/span&gt; T field, T value, &lt;span class="type"&gt;IEqualityComparer&lt;/span&gt;&amp;lt;T&amp;gt; comparer)
{
  DebugVerifySetPropertyCoreArguments(propertyName, comparer);
  &lt;span class="kwrd"&gt;if&lt;/span&gt; (!comparer.Equals(field, value))
  {
    T oldValue = field;
    field = value;
    &lt;span class="kwrd"&gt;try&lt;/span&gt;
    {
      OnPropertyChanged(&lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="type"&gt;PropertyChangedEventArgs&lt;/span&gt;(propertyName));
    }
    &lt;span class="kwrd"&gt;catch&lt;/span&gt;
    {
      field = oldValue;
      &lt;span class="kwrd"&gt;throw&lt;/span&gt;;
    }
  }
}&lt;/pre&gt;

&lt;p&gt;When errors cannot be avoided objects that support transactional behaviour, i.e. the strong guarantee, will result in more reliable programs. It’s worth noting that there are a few extreme scenarios where an exception is thrown but the code in the catch block is not executed. For example, if memory has become so scarce that any attempt to allocate more memory results in an &lt;a href="http://msdn.microsoft.com/en-gb/library/system.outofmemoryexception.aspx"&gt;OutOfMemoryException&lt;/a&gt; being thrown, subsequent attempts to allocate memory will also fail. Could any subsequent memory allocations occur in the catch block above? Yes. They will occur when the jitter attempts to generate the native code for the block. Obviously this is a catastrophic failure that will hopefully result in termination of the running process, so the chances of anyone observing or serialising the changed value are slim. For that reason I’m going to leave the catch block as it is. If you need greater reliability than offered by the catch block then you can look at the reliability APIs from the &lt;a href="http://msdn.microsoft.com/en-gb/library/system.runtime.compilerservices.aspx"&gt;System.Runtime.CompilerServices&lt;/a&gt; namespace, such as the &lt;a href="http://msdn.microsoft.com/en-gb/library/system.runtime.compilerservices.runtimehelpers.executecodewithguaranteedcleanup.aspx"&gt;RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup&lt;/a&gt; method.&lt;/p&gt;

&lt;p&gt;One wrinkle still remains, which is related to the threading model used for both &lt;em&gt;Windows Forms&lt;/em&gt; and &lt;em&gt;WPF&lt;/em&gt;. This threading model requires that operations on UI objects be made on the thread that created them. The &lt;em&gt;ObservableItem&lt;/em&gt; class is intended for use with data binding, which means we expect it to interact with UI objects. The class currently performs no checks to ensure that this interaction occurs on the correct thread. In &lt;a href="http://loadsofcode.blogspot.com/2009/02/implementing-observable-objects-part-vi.html"&gt;Part VI&lt;/a&gt; we’ll see how we can address this.&lt;/p&gt;
&lt;iframe style="border-right: #dde5e9 1px solid; padding-right: 0px; border-top: #dde5e9 1px solid; padding-left: 0px; padding-bottom: 0px; margin: 3px; border-left: #dde5e9 1px solid; width: 240px; padding-top: 0px; border-bottom: #dde5e9 1px solid; height: 66px; background-color: #ffffff" marginwidth="0" marginheight="0" src="http://cid-4fea45d461294bd0.skydrive.live.com/embedrowdetail.aspx/Public/LoadsOfCode/Implementing%20Observable%20Objects%20-%20Part%20V.zip" frameborder="0" scrolling="no"&gt;&lt;/iframe&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9201139154426574883-2560828741736952274?l=loadsofcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://loadsofcode.blogspot.com/feeds/2560828741736952274/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://loadsofcode.blogspot.com/2009/02/implementing-observable-objects-part-v.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/2560828741736952274'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/2560828741736952274'/><link rel='alternate' type='text/html' href='http://loadsofcode.blogspot.com/2009/02/implementing-observable-objects-part-v.html' title='Implementing Observable Objects – Part V'/><author><name>Kevin Westhead</name><uri>http://www.blogger.com/profile/05226243485559749240</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/-T93lAVSpKrI/Tu__lq-Ia9I/AAAAAAAAAII/tnKoAeDFrrs/s220/Kevin%2BWesthead%2B%2528grey%2529.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9201139154426574883.post-3053982620850120220</id><published>2009-02-02T23:00:00.002Z</published><updated>2009-02-13T04:12:31.224Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='WPF'/><category scheme='http://www.blogger.com/atom/ns#' term='Windows Forms'/><category scheme='http://www.blogger.com/atom/ns#' term='Implementing Observable Objects'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><title type='text'>Implementing Observable Objects – Part IV</title><content type='html'>&lt;p&gt;In &lt;a href="http://loadsofcode.blogspot.com/2009/01/implementing-observable-objects-part.html"&gt;Part III&lt;/a&gt; we looked at providing better diagnostic assistance for the &lt;em&gt;SetProperty&lt;/em&gt; method on the &lt;em&gt;ObservableItem&lt;/em&gt; class by asserting the relevant assumptions. Unfortunately this approach doesn't help third party users of our data model unless we give them access to debug builds. What we can do is modify the approach to match what the &lt;em&gt;Windows Forms&lt;/em&gt; team did for detecting illegal cross-thread calls and use exceptions instead of asserts. Essentially this means the default behaviour will be to throw an exception only when the debugger is attached, providing third parties with the opportunity to see exceptions when they are debugging. This is a reasonable compromise because we want to detect incorrect usage of the &lt;em&gt;SetProperty&lt;/em&gt; method but we don’t want to unnecessarily penalise the release build performance. The following static property indicates whether or not we want to verify the arguments to the &lt;em&gt;SetProperty&lt;/em&gt; method.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;private static bool&lt;/span&gt; s_verifySetPropertyArguments = &lt;span class="type"&gt;Debugger&lt;/span&gt;.IsAttached;

[&lt;span class="type"&gt;EditorBrowsable&lt;/span&gt;(&lt;span class="type"&gt;EditorBrowsableState&lt;/span&gt;.Advanced)]
&lt;span class="kwrd"&gt;public static bool&lt;/span&gt; VerifySetPropertyArguments
{
  &lt;span class="kwrd"&gt;get&lt;/span&gt; { &lt;span class="kwrd"&gt;return&lt;/span&gt; s_verifySetPropertyArguments; }
  &lt;span class="kwrd"&gt;set&lt;/span&gt; { s_verifySetPropertyArguments = &lt;span class="kwrd"&gt;value&lt;/span&gt;; }
}&lt;/pre&gt;

&lt;p&gt;The default value is determined by the &lt;a href="http://msdn.microsoft.com/en-gb/library/system.diagnostics.debugger.isattached.aspx"&gt;Debugger.IsAttached&lt;/a&gt; property but it can be changed to perform verification even when a debugger is not attached. This provides a limited amount of control over the behaviour of the &lt;em&gt;ObservableItem&lt;/em&gt; class, plus it also makes it easier to test the verification code. I’ve used the &lt;a href="http://msdn.microsoft.com/en-gb/library/system.componentmodel.editorbrowsableattribute.aspx"&gt;EditorBrowsableAttribute&lt;/a&gt; class with the &lt;a href="http://msdn.microsoft.com/en-gb/library/system.componentmodel.editorbrowsablestate.aspx"&gt;EditorBrowsableState.Advanced&lt;/a&gt; value to hide the property from &lt;em&gt;IntelliSense&lt;/em&gt; when advanced members are not enabled in the code editor. This is a reasonable approach because the default value is sufficient for all but the most advanced scenarios. The &lt;em&gt;SetPropertyInternal&lt;/em&gt; method can now use the property to determine whether or not to run the verification code, which is no longer confined to debug builds.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;[&lt;span class="type"&gt;MethodImpl&lt;/span&gt;(&lt;span class="type"&gt;MethodImplOptions&lt;/span&gt;.NoInlining)]
&lt;span class="kwrd"&gt;private void&lt;/span&gt; SetPropertyInternal&amp;lt;T&amp;gt;(
  &lt;span class="kwrd"&gt;string&lt;/span&gt; propertyName, &lt;span class="kwrd"&gt;ref&lt;/span&gt; T field, T value, &lt;span class="type"&gt;IEqualityComparer&lt;/span&gt;&amp;lt;T&amp;gt; comparer)
{
  &lt;span class="kwrd"&gt;if&lt;/span&gt; (VerifySetPropertyArguments)
  {
    VerifySetPropertyInternalArguments(propertyName, comparer);
  }
  &lt;span class="kwrd"&gt;if&lt;/span&gt; (!comparer.Equals(field, value))
  {
    field = value;
    OnPropertyChanged(&lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="type"&gt;PropertyChangedEventArgs&lt;/span&gt;(propertyName));
  }
}&lt;/pre&gt;

&lt;p&gt;The &lt;em&gt;VerifySetPropertyInternalArguments&lt;/em&gt; method no longer uses the &lt;a href="http://msdn.microsoft.com/en-gb/library/system.diagnostics.conditionalattribute.aspx"&gt;ConditionalAttribute&lt;/a&gt; class although it does still have some asserts.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;[&lt;span class="type"&gt;MethodImpl&lt;/span&gt;(&lt;span class="type"&gt;MethodImplOptions&lt;/span&gt;.NoInlining)]
&lt;span class="kwrd"&gt;private void&lt;/span&gt; VerifySetPropertyInternalArguments&amp;lt;T&amp;gt;(
  &lt;span class="kwrd"&gt;string&lt;/span&gt; propertyName, &lt;span class="type"&gt;IEqualityComparer&lt;/span&gt;&amp;lt;T&amp;gt; comparer)
{
  &lt;span class="type"&gt;Debug&lt;/span&gt;.Assert(
    VerifySetPropertyArguments,
    &lt;span class="str"&gt;&amp;quot;Invalid operation.&amp;quot;&lt;/span&gt;,
    &lt;span class="str"&gt;&amp;quot;This method should only be called when the 'VerifySetPropertyArguments' &amp;quot;&lt;/span&gt; + 
    &lt;span class="str"&gt;&amp;quot;property returns a value of true.&amp;quot;&lt;/span&gt;);
  &lt;span class="type"&gt;Debug&lt;/span&gt;.Assert(
    comparer != &lt;span class="kwrd"&gt;null&lt;/span&gt;, 
    &lt;span class="str"&gt;&amp;quot;Argument null.&amp;quot;&lt;/span&gt;, 
    &lt;span class="str"&gt;&amp;quot;Argument 'comparer' should not be a null reference.&amp;quot;&lt;/span&gt;);
  &lt;span class="kwrd"&gt;var&lt;/span&gt; type = GetType();
  &lt;span class="kwrd"&gt;var&lt;/span&gt; propertyType = &lt;span class="kwrd"&gt;typeof&lt;/span&gt;(T);
  &lt;span class="type"&gt;PropertyInfo&lt;/span&gt; property = type.GetProperty(propertyName, propertyType);
  &lt;span class="kwrd"&gt;if&lt;/span&gt; (property == &lt;span class="kwrd"&gt;null&lt;/span&gt;)
  {
    &lt;span class="kwrd"&gt;throw new&lt;/span&gt; &lt;span class="type"&gt;ArgumentException&lt;/span&gt;(
      &lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(
        &lt;span class="type"&gt;CultureInfo&lt;/span&gt;.InvariantCulture,
        &lt;span class="str"&gt;&amp;quot;The argument does not represent the name of a property on this type with &amp;quot;&lt;/span&gt; +
        &lt;span class="str"&gt;&amp;quot;the expected return type. One or more of the following values is wrong.\n\n&amp;quot;&lt;/span&gt; +
        &lt;span class="str"&gt;&amp;quot;Type: {0}\nProperty name: {1}\nProperty type: {2}&amp;quot;&lt;/span&gt;,
        type.FullName, propertyName, propertyType.FullName),
      &lt;span class="str"&gt;&amp;quot;propertyName&amp;quot;&lt;/span&gt;);
  }
  &lt;span class="kwrd"&gt;else&lt;/span&gt;
  {
    &lt;span class="type"&gt;MethodBase&lt;/span&gt; expectedSetMethod = property.GetSetMethod();
    &lt;span class="kwrd"&gt;var&lt;/span&gt; frame = &lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="type"&gt;StackFrame&lt;/span&gt;(3);
    &lt;span class="type"&gt;MethodBase&lt;/span&gt; actualSetMethod = frame.GetMethod();
    &lt;span class="kwrd"&gt;if&lt;/span&gt; (actualSetMethod != expectedSetMethod)
    {
      &lt;span class="kwrd"&gt;throw new&lt;/span&gt; &lt;span class="type"&gt;ArgumentException&lt;/span&gt;(
        &lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(
          &lt;span class="type"&gt;CultureInfo&lt;/span&gt;.InvariantCulture,
          &lt;span class="str"&gt;&amp;quot;The argument does not match the name of the property being set.\n\n&amp;quot;&lt;/span&gt; +
          &lt;span class="str"&gt;&amp;quot;Expected property set method: {0}\nActual property set method: {1}&amp;quot;&lt;/span&gt;,
          expectedSetMethod, actualSetMethod),
        &lt;span class="str"&gt;&amp;quot;propertyName&amp;quot;&lt;/span&gt;);
      }
    }
  }
}&lt;/pre&gt;

&lt;p&gt;The first assert ensures the method is being called only when necessary and the second assert has been retained from Part III because there should always be a comparer. The key difference is that we now throw an &lt;a href="http://msdn.microsoft.com/en-gb/library/system.argumentexception.aspx"&gt;ArgumentException&lt;/a&gt; when detecting incorrect usage. If the expected property cannot be found you’ll see the following exception details:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://lh3.ggpht.com/_0dLBalBcXaI/SYeFfXMeEEI/AAAAAAAAADw/Awd2l2NZswY/s1600-h/Property%20Not%20Found%20Exception%5B3%5D.png"&gt;&lt;img title="Property Not Found Exception" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="345" alt="Property Not Found Exception" src="http://lh4.ggpht.com/_0dLBalBcXaI/SYeFf_v5MCI/AAAAAAAAAD0/sNCgVMY4IKQ/Property%20Not%20Found%20Exception_thumb%5B1%5D.png?imgmax=800" width="456" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;If the wrong property setter is being called you’ll see the following exception details:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://lh6.ggpht.com/_0dLBalBcXaI/SYeFgAWqr1I/AAAAAAAAAD4/lZMRh_Mhi5M/s1600-h/Invalid%20Property%20Setter%20Exception%5B3%5D.png"&gt;&lt;img title="Invalid Property Setter Exception" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="320" alt="Invalid Property Setter Exception" src="http://lh5.ggpht.com/_0dLBalBcXaI/SYeFgtALQlI/AAAAAAAAAD8/oRT6rTtct6Q/Invalid%20Property%20Setter%20Exception_thumb%5B1%5D.png?imgmax=800" width="456" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;You’ve probably noticed the &lt;a href="http://msdn.microsoft.com/en-gb/library/system.runtime.compilerservices.methodimplattribute.aspx"&gt;MethodImplAttribute&lt;/a&gt; class on the methods above with the &lt;a href="http://msdn.microsoft.com/en-gb/library/system.runtime.compilerservices.methodimploptions.aspx"&gt;MethodImplOptions.NoInlining&lt;/a&gt; value. Even though the default behaviour is for the verification code to only run under the debugger, we can’t assume that will always be the case. This means we don’t know if the jitter has applied optimisations, such as method inlining, which could cause the verification code to produce false positives. Using the &lt;em&gt;NoInlining&lt;/em&gt; value prevents a method from being inlined, ensuring that the verification code performs as expected.&lt;/p&gt;

&lt;p&gt;The next issue to address is that the &lt;em&gt;SetPropertyInternal&lt;/em&gt; method can call unknown code. In &lt;a href="http://loadsofcode.blogspot.com/2009/02/implementing-observable-objects-part-v.html"&gt;Part V&lt;/a&gt; we'll look at how this can occur, why it's a problem and how we can fix it.&lt;/p&gt;
&lt;iframe style="border-right: #dde5e9 1px solid; padding-right: 0px; border-top: #dde5e9 1px solid; padding-left: 0px; padding-bottom: 0px; margin: 3px; border-left: #dde5e9 1px solid; width: 240px; padding-top: 0px; border-bottom: #dde5e9 1px solid; height: 66px; background-color: #ffffff" marginwidth="0" marginheight="0" src="http://cid-4fea45d461294bd0.skydrive.live.com/embedrowdetail.aspx/Public/LoadsOfCode/Implementing%20Observable%20Objects%20-%20Part%20IV.zip" frameborder="0" scrolling="no"&gt;&lt;/iframe&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9201139154426574883-3053982620850120220?l=loadsofcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://loadsofcode.blogspot.com/feeds/3053982620850120220/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://loadsofcode.blogspot.com/2009/02/implementing-observable-objects-part-iv.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/3053982620850120220'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/3053982620850120220'/><link rel='alternate' type='text/html' href='http://loadsofcode.blogspot.com/2009/02/implementing-observable-objects-part-iv.html' title='Implementing Observable Objects – Part IV'/><author><name>Kevin Westhead</name><uri>http://www.blogger.com/profile/05226243485559749240</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/-T93lAVSpKrI/Tu__lq-Ia9I/AAAAAAAAAII/tnKoAeDFrrs/s220/Kevin%2BWesthead%2B%2528grey%2529.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://lh4.ggpht.com/_0dLBalBcXaI/SYeFf_v5MCI/AAAAAAAAAD0/sNCgVMY4IKQ/s72-c/Property%20Not%20Found%20Exception_thumb%5B1%5D.png?imgmax=800' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9201139154426574883.post-2083511089401185599</id><published>2009-01-28T23:00:00.001Z</published><updated>2009-02-13T04:10:26.660Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='WPF'/><category scheme='http://www.blogger.com/atom/ns#' term='Windows Forms'/><category scheme='http://www.blogger.com/atom/ns#' term='Implementing Observable Objects'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><title type='text'>Implementing Observable Objects – Part III</title><content type='html'>&lt;p&gt;In &lt;a href="http://loadsofcode.blogspot.com/2009/01/implementing-observable-objects-part-ii.html"&gt;Part II&lt;/a&gt; we saw the introduction of the &lt;em&gt;ObservableItem&lt;/em&gt; base class, which simplifies the property update mechanism by placing all of the boilerplate code in the &lt;em&gt;SetProperty&lt;/em&gt; method. The problem with this approach is that it’s too easy to make a mistake with the property names, so now we’re going to reinforce the &lt;em&gt;SetProperty&lt;/em&gt; method by asserting the relevant assumptions. These assumptions are:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;A property with the specified name exists on the type. &lt;/li&gt;
  &lt;li&gt;The invoked method is the property setter for the property with the specified name. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To facilitate this we need to restructure the &lt;em&gt;SetProperty&lt;/em&gt; method so that both overloads funnel through to the same method. I’ll explain why this is necessary in more detail later, but for now here’s the new structure:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;protected void&lt;/span&gt; SetProperty&amp;lt;T&amp;gt;(&lt;span class="kwrd"&gt;string&lt;/span&gt; propertyName, &lt;span class="kwrd"&gt;ref&lt;/span&gt; T field, T value)
{
  SetPropertyInternal(propertyName, &lt;span class="kwrd"&gt;ref&lt;/span&gt; field, value, &lt;span class="type"&gt;EqualityComparer&lt;/span&gt;&amp;lt;T&amp;gt;.Default);
}

&lt;span class="kwrd"&gt;protected void&lt;/span&gt; SetProperty&amp;lt;T&amp;gt;(
  &lt;span class="kwrd"&gt;string&lt;/span&gt; propertyName, &lt;span class="kwrd"&gt;ref&lt;/span&gt; T field, T value, &lt;span class="type"&gt;IEqualityComparer&lt;/span&gt;&amp;lt;T&amp;gt; comparer)
{
  SetPropertyInternal(
    propertyName, 
    &lt;span class="kwrd"&gt;ref&lt;/span&gt; field, 
    value, 
    comparer == &lt;span class="kwrd"&gt;null&lt;/span&gt; ? &lt;span class="type"&gt;EqualityComparer&lt;/span&gt;&amp;lt;T&amp;gt;.Default : comparer);
}

&lt;span class="kwrd"&gt;private void&lt;/span&gt; SetPropertyInternal&amp;lt;T&amp;gt;(
  &lt;span class="kwrd"&gt;string&lt;/span&gt; propertyName, &lt;span class="kwrd"&gt;ref&lt;/span&gt; T field, T value, &lt;span class="type"&gt;IEqualityComparer&lt;/span&gt;&amp;lt;T&amp;gt; comparer)
{
  DebugVerifySetPropertyInternalArguments(propertyName, comparer);
  &lt;span class="kwrd"&gt;if&lt;/span&gt; (!comparer.Equals(field, value))
  {
    field = value;
    OnPropertyChanged(&lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="type"&gt;PropertyChangedEventArgs&lt;/span&gt;(propertyName));
  }
}&lt;/pre&gt;

&lt;p&gt;Not a huge change as you can see. The implementation is essentially the same although there’s a new method – &lt;em&gt;DebugVerifySetPropertyInternalArguments&lt;/em&gt; – called before the equality check. This is the method that contains the relevant asserts.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;[&lt;span class="type"&gt;Conditional&lt;/span&gt;(&lt;span class="str"&gt;&amp;quot;DEBUG&amp;quot;&lt;/span&gt;)]
&lt;span class="kwrd"&gt;private void&lt;/span&gt; DebugVerifySetPropertyInternalArguments&amp;lt;T&amp;gt;(
  &lt;span class="kwrd"&gt;string&lt;/span&gt; propertyName, &lt;span class="type"&gt;IEqualityComparer&lt;/span&gt;&amp;lt;T&amp;gt; comparer)
{
  &lt;span class="type"&gt;Debug&lt;/span&gt;.Assert(
    comparer != &lt;span class="kwrd"&gt;null&lt;/span&gt;, 
    &lt;span class="str"&gt;&amp;quot;Argument null.&amp;quot;&lt;/span&gt;, 
    &lt;span class="str"&gt;&amp;quot;Argument 'comparer' should not be a null reference.&amp;quot;&lt;/span&gt;);
  &lt;span class="kwrd"&gt;var&lt;/span&gt; type = GetType();
  &lt;span class="kwrd"&gt;var&lt;/span&gt; propertyType = &lt;span class="kwrd"&gt;typeof&lt;/span&gt;(T);
  &lt;span class="type"&gt;PropertyInfo&lt;/span&gt; property = type.GetProperty(propertyName, propertyType);
  &lt;span class="kwrd"&gt;if&lt;/span&gt; (property == &lt;span class="kwrd"&gt;null&lt;/span&gt;)
  {
    &lt;span class="type"&gt;Debug&lt;/span&gt;.Fail(
      &lt;span class="str"&gt;&amp;quot;Argument invalid.&amp;quot;&lt;/span&gt;,
      &lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(
        &lt;span class="type"&gt;CultureInfo&lt;/span&gt;.InvariantCulture,
        &lt;span class="str"&gt;&amp;quot;Argument 'propertyName' does not represent the name of a property on this &amp;quot;&lt;/span&gt; +
        &lt;span class="str"&gt;&amp;quot;type with the expected return type. One or more of the following values &amp;quot;&lt;/span&gt; +
        &lt;span class="str"&gt;&amp;quot;is wrong.\n\nType: {0}\nProperty name: {1}\nProperty type: {2}&amp;quot;&lt;/span&gt;,
        type.FullName, propertyName, propertyType.FullName));
  }
  &lt;span class="kwrd"&gt;else&lt;/span&gt;
  {
    &lt;span class="type"&gt;MethodBase&lt;/span&gt; expectedSetMethod = property.GetSetMethod();
    &lt;span class="kwrd"&gt;var&lt;/span&gt; frame = &lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="type"&gt;StackFrame&lt;/span&gt;(3);
    &lt;span class="type"&gt;MethodBase&lt;/span&gt; actualSetMethod = frame.GetMethod();
    &lt;span class="type"&gt;Debug&lt;/span&gt;.Assert(
      actualSetMethod == expectedSetMethod,
      &lt;span class="str"&gt;&amp;quot;Argument invalid.&amp;quot;&lt;/span&gt;,
      &lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(
        &lt;span class="type"&gt;CultureInfo&lt;/span&gt;.InvariantCulture,
        &lt;span class="str"&gt;&amp;quot;Argument 'propertyName' does not match the name of the property being &amp;quot;&lt;/span&gt; +
        &lt;span class="str"&gt;&amp;quot;set.\n\nExpected property set method: {0}\nActual property set method: {1}&amp;quot;&lt;/span&gt;,
        expectedSetMethod, actualSetMethod));
  }
}&lt;/pre&gt;

&lt;p&gt;The first assert verifies that we have a comparer, otherwise we have no way of knowing whether or not the value has changed. The second assert verifies that the type has a property with the correct name and return type. If you make a mistake like specifying a non-existent property name, then you’ll see the following message under the debugger:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://lh6.ggpht.com/_0dLBalBcXaI/SYDyOfTcWVI/AAAAAAAAADQ/71LvKX-17FI/s1600-h/Property%20Not%20Found%20Assert%5B3%5D.png"&gt;&lt;img title="Property Not Found Assert" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="288" alt="Property Not Found Assert" src="http://lh4.ggpht.com/_0dLBalBcXaI/SYDyPNS7E3I/AAAAAAAAADU/pmwsTSnklm0/Property%20Not%20Found%20Assert_thumb%5B1%5D.png?imgmax=800" width="500" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;The final assert verifies that once we have identified a property with the correct name and return type, the property’s set method matches the method being invoked. This is why we had to restructure the overloads, because the invoked method is retrieved from a &lt;a href="http://msdn.microsoft.com/en-gb/library/system.diagnostics.stackframe.aspx"&gt;StackFrame&lt;/a&gt;. Having all of the &lt;em&gt;SetProperty&lt;/em&gt; overloads call &lt;em&gt;SetPropertyInternal&lt;/em&gt; means we always know how many frames to skip to get to the property setter. If you make a mistake like specifying an existing property name in the wrong property setter, then you’ll see the following message under the debugger:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://lh3.ggpht.com/_0dLBalBcXaI/SYDyPnJIZ2I/AAAAAAAAADY/7XKMHx9Jog8/s1600-h/Invalid%20Property%20Setter%20Assert%5B3%5D.png"&gt;&lt;img title="Invalid Property Setter Assert" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="259" alt="Invalid Property Setter Assert" src="http://lh5.ggpht.com/_0dLBalBcXaI/SYDyQTjfmgI/AAAAAAAAADc/gLLOlfSz1OA/Invalid%20Property%20Setter%20Assert_thumb%5B1%5D.png?imgmax=800" width="500" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;Both of these messages are extremely useful for quickly and accurately tracking down typos and copy/paste errors in debug builds.&lt;/p&gt;

&lt;p&gt;The observant among you will no doubt have spotted that there are still a few issues. One of which is that the &lt;em&gt;ObservableItem&lt;/em&gt; class is public and the &lt;em&gt;SetProperty&lt;/em&gt; overloads are therefore part of its public API. Now it’s entirely possible for your data model assembly to be a private assembly, i.e. an assembly that isn’t intended or authorised to be used by third parties. When this isn’t the case however, we can’t rely on the use of asserts because third parties are unlikely to be using debug builds of your data model. Another worry is that we can conveniently ignore the overhead of using reflection and interrogating the call stack with the asserts because they’ll only execute in debug builds. We really don’t won’t to incur this overhead at such a low level in our data model for release builds. In &lt;a href="http://loadsofcode.blogspot.com/2009/02/implementing-observable-objects-part-iv.html"&gt;Part IV&lt;/a&gt; we’ll look at an approach that provides the same level of diagnostic assistance as the asserts described here but without requiring access to a debug build of the data model and without unnecessarily penalising the release build performance.&lt;/p&gt;
&lt;iframe style="border-right: #dde5e9 1px solid; padding-right: 0px; border-top: #dde5e9 1px solid; padding-left: 0px; padding-bottom: 0px; margin: 3px; border-left: #dde5e9 1px solid; width: 240px; padding-top: 0px; border-bottom: #dde5e9 1px solid; height: 66px; background-color: #ffffff" marginwidth="0" marginheight="0" src="http://cid-4fea45d461294bd0.skydrive.live.com/embedrowdetail.aspx/Public/LoadsOfCode/Implementing%20Observable%20Objects%20-%20Part%20III.zip" frameborder="0" scrolling="no"&gt;&lt;/iframe&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9201139154426574883-2083511089401185599?l=loadsofcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://loadsofcode.blogspot.com/feeds/2083511089401185599/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://loadsofcode.blogspot.com/2009/01/implementing-observable-objects-part.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/2083511089401185599'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/2083511089401185599'/><link rel='alternate' type='text/html' href='http://loadsofcode.blogspot.com/2009/01/implementing-observable-objects-part.html' title='Implementing Observable Objects – Part III'/><author><name>Kevin Westhead</name><uri>http://www.blogger.com/profile/05226243485559749240</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/-T93lAVSpKrI/Tu__lq-Ia9I/AAAAAAAAAII/tnKoAeDFrrs/s220/Kevin%2BWesthead%2B%2528grey%2529.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://lh4.ggpht.com/_0dLBalBcXaI/SYDyPNS7E3I/AAAAAAAAADU/pmwsTSnklm0/s72-c/Property%20Not%20Found%20Assert_thumb%5B1%5D.png?imgmax=800' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9201139154426574883.post-7890759356621579540</id><published>2009-01-27T23:00:00.001Z</published><updated>2009-02-13T04:08:23.037Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='WPF'/><category scheme='http://www.blogger.com/atom/ns#' term='Windows Forms'/><category scheme='http://www.blogger.com/atom/ns#' term='Implementing Observable Objects'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><title type='text'>Implementing Observable Objects – Part II</title><content type='html'>&lt;p&gt;In &lt;a href="http://loadsofcode.blogspot.com/2009/01/implementing-observable-objects-part-i.html"&gt;Part I&lt;/a&gt; we looked at a very straightforward implementation of the &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx"&gt;INotifyPropertyChanged&lt;/a&gt; interface to create an observable object. Unfortunately there aren’t many data models where one observable object with two properties will suffice &lt;font face="Wingdings"&gt;J&lt;/font&gt;. This means you can find yourself repeating a lot of boilerplate code in each property setter. We can use the following base class to make implementing the property setters a little more trivial:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public abstract class&lt;/span&gt; &lt;span class="type"&gt;ObservableItem&lt;/span&gt; : &lt;span class="type"&gt;INotifyPropertyChanged&lt;/span&gt;
{
  &lt;span class="kwrd"&gt;protected&lt;/span&gt; ObservableItem()
    : &lt;span class="kwrd"&gt;base&lt;/span&gt;()
  {
  }

  &lt;span class="kwrd"&gt;public event&lt;/span&gt; &lt;span class="type"&gt;PropertyChangedEventHandler&lt;/span&gt; PropertyChanged;

  &lt;span class="kwrd"&gt;protected virtual void&lt;/span&gt; OnPropertyChanged(&lt;span class="type"&gt;PropertyChangedEventArgs&lt;/span&gt; e)
  {
    &lt;span class="type"&gt;PropertyChangedEventHandler&lt;/span&gt; handler = PropertyChanged;
    &lt;span class="kwrd"&gt;if&lt;/span&gt; (handler != &lt;span class="kwrd"&gt;null&lt;/span&gt;)
    {
      handler(&lt;span class="kwrd"&gt;this&lt;/span&gt;, e);
    }
  }

  &lt;span class="kwrd"&gt;protected void&lt;/span&gt; SetProperty&amp;lt;T&amp;gt;(&lt;span class="kwrd"&gt;string&lt;/span&gt; propertyName, &lt;span class="kwrd"&gt;ref&lt;/span&gt; T field, T value)
  {
    SetProperty(propertyName, &lt;span class="kwrd"&gt;ref&lt;/span&gt; field, value, &lt;span class="kwrd"&gt;null&lt;/span&gt;);
  }

  &lt;span class="kwrd"&gt;protected void&lt;/span&gt; SetProperty&amp;lt;T&amp;gt;(
    &lt;span class="kwrd"&gt;string&lt;/span&gt; propertyName, &lt;span class="kwrd"&gt;ref&lt;/span&gt; T field, T value, &lt;span class="type"&gt;IEqualityComparer&lt;/span&gt;&amp;lt;T&amp;gt; comparer)
  {
    &lt;span class="kwrd"&gt;if&lt;/span&gt; (comparer == &lt;span class="kwrd"&gt;null&lt;/span&gt;)
    {
      comparer = &lt;span class="type"&gt;EqualityComparer&lt;/span&gt;&amp;lt;T&amp;gt;.Default;
    }
    &lt;span class="kwrd"&gt;if&lt;/span&gt; (!comparer.Equals(field, value))
    {
      field = value;
      OnPropertyChanged(&lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="type"&gt;PropertyChangedEventArgs&lt;/span&gt;(propertyName));
    }
  }
}&lt;/pre&gt;

&lt;p&gt;The &lt;em&gt;SetProperty&lt;/em&gt; method compares the current value in a property’s backing field with the new value and raises the &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.propertychanged.aspx"&gt;PropertyChanged&lt;/a&gt; event if the value has changed. In order to update the property’s backing field we have to pass it by reference. For those of you that make use of the code analysis support in &lt;em&gt;Visual Studio&lt;/em&gt;, you’ll notice that the &lt;em&gt;SetProperty&lt;/em&gt; method actually violates the &lt;a href="http://msdn.microsoft.com/en-us/library/ms182146.aspx"&gt;DoNotPassTypesByReference&lt;/a&gt; rule. I think this is a justifiable violation given that it improves the maintainability of you observable objects, so I always add the following suppression:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;[&lt;span class="type"&gt;SuppressMessage&lt;/span&gt;(
  &lt;span class="str"&gt;&amp;quot;Microsoft.Design&amp;quot;&lt;/span&gt;, 
  &lt;span class="str"&gt;&amp;quot;CA1045:DoNotPassTypesByReference&amp;quot;&lt;/span&gt;, 
  Justification = 
    &lt;span class="str"&gt;&amp;quot;This method performs the common functionality required for setting a &amp;quot;&lt;/span&gt; + 
    &lt;span class="str"&gt;&amp;quot;property, which includes raising events. To set the value of the property's &amp;quot;&lt;/span&gt; + 
    &lt;span class="str"&gt;&amp;quot;backing field, the backing field must be passed by reference.&amp;quot;&lt;/span&gt;, 
  MessageId = &lt;span class="str"&gt;&amp;quot;1#&amp;quot;&lt;/span&gt;)]&lt;/pre&gt;

&lt;p&gt;Now we can re-write the &lt;em&gt;Person&lt;/em&gt; class as follows:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public class&lt;/span&gt; &lt;span class="type"&gt;Person&lt;/span&gt; : &lt;span class="type"&gt;ObservableItem&lt;/span&gt;
{
  &lt;span class="kwrd"&gt;private string&lt;/span&gt; m_firstName;
  &lt;span class="kwrd"&gt;private string&lt;/span&gt; m_lastName;

  &lt;span class="kwrd"&gt;public string&lt;/span&gt; FirstName
  {
    &lt;span class="kwrd"&gt;get&lt;/span&gt; { &lt;span class="kwrd"&gt;return&lt;/span&gt; m_firstName; }
    &lt;span class="kwrd"&gt;set&lt;/span&gt; { SetProperty(&lt;span class="str"&gt;&amp;quot;FirstName&amp;quot;&lt;/span&gt;, &lt;span class="kwrd"&gt;ref&lt;/span&gt; m_firstName, &lt;span class="kwrd"&gt;value&lt;/span&gt;, &lt;span class="type"&gt;StringComparer&lt;/span&gt;.Ordinal); }
  }

  &lt;span class="kwrd"&gt;public string&lt;/span&gt; LastName
  {
    &lt;span class="kwrd"&gt;get&lt;/span&gt; { &lt;span class="kwrd"&gt;return&lt;/span&gt; m_lastName; }
    &lt;span class="kwrd"&gt;set&lt;/span&gt; { SetProperty(&lt;span class="str"&gt;&amp;quot;LastName&amp;quot;&lt;/span&gt;, &lt;span class="kwrd"&gt;ref&lt;/span&gt; m_lastName, &lt;span class="kwrd"&gt;value&lt;/span&gt;, &lt;span class="type"&gt;StringComparer&lt;/span&gt;.Ordinal); }
  }
}&lt;/pre&gt;

&lt;p&gt;The property setters now contain just one line of code but we're not done yet. A weakness of this approach is that with an unfortunate typo – an occupational hazard in software development &lt;font face="Wingdings"&gt;J&lt;/font&gt; –or with some copy/paste abuse we can end up supplying the wrong property name to the &lt;em&gt;SetProperty&lt;/em&gt; method. In &lt;a href="http://loadsofcode.blogspot.com/2009/01/implementing-observable-objects-part.html"&gt;Part III&lt;/a&gt; we’ll look at making the &lt;em&gt;SetProperty&lt;/em&gt; method more robust to these mistakes.&lt;/p&gt;
&lt;iframe style="border-right: #dde5e9 1px solid; padding-right: 0px; border-top: #dde5e9 1px solid; padding-left: 0px; padding-bottom: 0px; margin: 3px; border-left: #dde5e9 1px solid; width: 240px; padding-top: 0px; border-bottom: #dde5e9 1px solid; height: 66px; background-color: #ffffff" marginwidth="0" marginheight="0" src="http://cid-4fea45d461294bd0.skydrive.live.com/embedrowdetail.aspx/Public/LoadsOfCode/Implementing%20Observable%20Objects%20-%20Part%20II.zip" frameborder="0" scrolling="no"&gt;&lt;/iframe&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9201139154426574883-7890759356621579540?l=loadsofcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://loadsofcode.blogspot.com/feeds/7890759356621579540/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://loadsofcode.blogspot.com/2009/01/implementing-observable-objects-part-ii.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/7890759356621579540'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/7890759356621579540'/><link rel='alternate' type='text/html' href='http://loadsofcode.blogspot.com/2009/01/implementing-observable-objects-part-ii.html' title='Implementing Observable Objects – Part II'/><author><name>Kevin Westhead</name><uri>http://www.blogger.com/profile/05226243485559749240</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/-T93lAVSpKrI/Tu__lq-Ia9I/AAAAAAAAAII/tnKoAeDFrrs/s220/Kevin%2BWesthead%2B%2528grey%2529.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9201139154426574883.post-5678593130167935309</id><published>2009-01-26T23:00:00.001Z</published><updated>2010-08-27T23:50:08.643+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='WPF'/><category scheme='http://www.blogger.com/atom/ns#' term='Windows Forms'/><category scheme='http://www.blogger.com/atom/ns#' term='Implementing Observable Objects'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><title type='text'>Implementing Observable Objects – Part I</title><content type='html'>&lt;p&gt;Whether you writing a &lt;em&gt;Windows Forms&lt;/em&gt; or &lt;em&gt;WPF&lt;/em&gt; application there’s a good chance you'll want to leverage the support both platforms have for data binding by constructing a data model that can be observed by the views in you application. One way to achieve this in &lt;em&gt;.NET&lt;/em&gt; is by implementing the &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx"&gt;INotifyPropertyChanged&lt;/a&gt; interface, which is supported by the data binding mechanisms of &lt;em&gt;Windows Forms&lt;/em&gt; and &lt;em&gt;WPF&lt;/em&gt;. Here’s a very simple example:&lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public class&lt;/span&gt; &lt;span class="type"&gt;Person&lt;/span&gt; : &lt;span class="type"&gt;INotifyPropertyChanged&lt;/span&gt;
{
  &lt;span class="kwrd"&gt;private string&lt;/span&gt; m_firstName;
  &lt;span class="kwrd"&gt;private string&lt;/span&gt; m_lastName;

  &lt;span class="kwrd"&gt;public&lt;/span&gt; Person() 
    : &lt;span class="kwrd"&gt;base&lt;/span&gt;()
  {
  }

  &lt;span class="kwrd"&gt;public event&lt;/span&gt; &lt;span class="type"&gt;PropertyChangedEventHandler&lt;/span&gt; PropertyChanged;

  &lt;span class="kwrd"&gt;public string&lt;/span&gt; FirstName
  {
    &lt;span class="kwrd"&gt;get&lt;/span&gt; { &lt;span class="kwrd"&gt;return&lt;/span&gt; m_firstName; }
    &lt;span class="kwrd"&gt;set&lt;/span&gt;
    {
      &lt;span class="kwrd"&gt;if&lt;/span&gt; (!&lt;span class="kwrd"&gt;string&lt;/span&gt;.Equals(m_firstName, &lt;span class="kwrd"&gt;value&lt;/span&gt;, &lt;span class="type"&gt;StringComparison&lt;/span&gt;.Ordinal))
      {
        m_firstName = &lt;span class="kwrd"&gt;value&lt;/span&gt;;
        OnPropertyChanged(&lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="type"&gt;PropertyChangedEventArgs&lt;/span&gt;(&lt;span class="str"&gt;&amp;quot;FirstName&amp;quot;&lt;/span&gt;));
      }
    }
  }

  &lt;span class="kwrd"&gt;public string&lt;/span&gt; LastName
  {
    &lt;span class="kwrd"&gt;get&lt;/span&gt; { &lt;span class="kwrd"&gt;return&lt;/span&gt; m_lastName; }
    &lt;span class="kwrd"&gt;set&lt;/span&gt;
    {
      &lt;span class="kwrd"&gt;if&lt;/span&gt; (!&lt;span class="kwrd"&gt;string&lt;/span&gt;.Equals(m_lastName, &lt;span class="kwrd"&gt;value&lt;/span&gt;, &lt;span class="type"&gt;StringComparison&lt;/span&gt;.Ordinal))
      {
        m_lastName = &lt;span class="kwrd"&gt;value&lt;/span&gt;;
        OnPropertyChanged(&lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="type"&gt;PropertyChangedEventArgs&lt;/span&gt;(&lt;span class="str"&gt;&amp;quot;LastName&amp;quot;&lt;/span&gt;));
      }
    }
  }

  &lt;span class="kwrd"&gt;protected virtual void&lt;/span&gt; OnPropertyChanged(&lt;span class="type"&gt;PropertyChangedEventArgs&lt;/span&gt; e)
  {
    &lt;span class="type"&gt;PropertyChangedEventHandler&lt;/span&gt; handler = PropertyChanged;
    &lt;span class="kwrd"&gt;if&lt;/span&gt; (handler != &lt;span class="kwrd"&gt;null&lt;/span&gt;)
    {
      handler(&lt;span class="kwrd"&gt;this&lt;/span&gt;, e);
    }
  }
}&lt;/pre&gt;

&lt;p&gt;That’s all there is to it. Views that data bind to the &lt;em&gt;Person&lt;/em&gt; object will automatically update when either the &lt;em&gt;FirstName&lt;/em&gt; or &lt;em&gt;LastName&lt;/em&gt; properties are changed. You can download sample &lt;em&gt;WPF&lt;/em&gt; and &lt;em&gt;Windows Forms&lt;/em&gt; applications demonstrating this using the link at the bottom of this post. Both applications are very simple – they contain a list control that is data bound to a collection of &lt;em&gt;Person&lt;/em&gt; objects and two text boxes that are data bound to the &lt;em&gt;FirstName&lt;/em&gt; and &lt;em&gt;LastName&lt;/em&gt; properties of the selected item in the list control. The screenshot below is from the &lt;em&gt;WPF&lt;/em&gt; application.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://lh6.ggpht.com/_0dLBalBcXaI/SXOOL20HJKI/AAAAAAAAABk/b-24NkINz8Y/s1600-h/WPF%20Sample%20Application%5B8%5D.png"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="WPF Sample Application" border="0" alt="WPF Sample Application" src="http://lh5.ggpht.com/_0dLBalBcXaI/SXOOMQjsm4I/AAAAAAAAABo/SaUH3dFAoaM/WPF%20Sample%20Application_thumb%5B4%5D.png?imgmax=800" width="551" height="391" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;Now, there’s nothing terribly wrong with the &lt;em&gt;Person&lt;/em&gt; object in this example but you’ll probably have more than two properties on your data model objects and it can become cumbersome writing similar code for each property setter. In &lt;a href="http://loadsofcode.blogspot.com/2009/01/implementing-observable-objects-part-ii.html"&gt;Part II&lt;/a&gt; we’ll look at reducing this burden.&lt;/p&gt;
&lt;iframe style="border-bottom: #dde5e9 1px solid; border-left: #dde5e9 1px solid; padding-bottom: 0px; background-color: #ffffff; margin: 3px; padding-left: 0px; width: 240px; padding-right: 0px; height: 66px; border-top: #dde5e9 1px solid; border-right: #dde5e9 1px solid; padding-top: 0px" marginheight="0" src="http://cid-4fea45d461294bd0.skydrive.live.com/embedrowdetail.aspx/Public/LoadsOfCode/Implementing%20Observable%20Objects%20-%20Part%20I.zip" frameborder="0" marginwidth="0" scrolling="no"&gt;&lt;/iframe&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9201139154426574883-5678593130167935309?l=loadsofcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://loadsofcode.blogspot.com/feeds/5678593130167935309/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://loadsofcode.blogspot.com/2009/01/implementing-observable-objects-part-i.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/5678593130167935309'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/5678593130167935309'/><link rel='alternate' type='text/html' href='http://loadsofcode.blogspot.com/2009/01/implementing-observable-objects-part-i.html' title='Implementing Observable Objects – Part I'/><author><name>Kevin Westhead</name><uri>http://www.blogger.com/profile/05226243485559749240</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/-T93lAVSpKrI/Tu__lq-Ia9I/AAAAAAAAAII/tnKoAeDFrrs/s220/Kevin%2BWesthead%2B%2528grey%2529.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://lh5.ggpht.com/_0dLBalBcXaI/SXOOMQjsm4I/AAAAAAAAABo/SaUH3dFAoaM/s72-c/WPF%20Sample%20Application_thumb%5B4%5D.png?imgmax=800' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9201139154426574883.post-5502703287032806785</id><published>2009-01-23T23:00:00.000Z</published><updated>2009-01-29T00:27:29.190Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='Unit Testing'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><title type='text'>Unit Testing Expected Exceptions</title><content type='html'>&lt;p&gt;Both &lt;a href="http://nunit.com/index.php?p=home"&gt;NUnit&lt;/a&gt; and &lt;em&gt;Visual Studio&lt;/em&gt; use an attribute to specify that an exception is expected during execution of a test. The problem with this approach is that it could hide bugs when the expected exception is thrown by a method that we did not expect to throw. In other words, even though the test passes we’re not testing what we think we’re testing. What we really want is a way of providing a scope for the exception that’s more granular than the scope of the entire test. Here are a few options for achieving this:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Use &lt;a href="http://www.codeplex.com/xunit"&gt;xUnit.net&lt;/a&gt;, which has a generic &lt;em&gt;Throws&lt;/em&gt; method on its &lt;em&gt;Assert&lt;/em&gt; class to specify that a provided delegate should throw an exception. &lt;/li&gt;    &lt;li&gt;Use &lt;a href="http://nunit.com/index.php?p=docHome&amp;amp;r=2.5"&gt;NUnit 2.5&lt;/a&gt;, which is currently still in beta. This brings &lt;em&gt;NUnit&lt;/em&gt; inline with &lt;em&gt;xUnit.net&lt;/em&gt; by adding a similar generic &lt;em&gt;Throws&lt;/em&gt; method to its &lt;em&gt;Assert&lt;/em&gt; class, plus it extends the constraint model with a &lt;em&gt;Throws&lt;/em&gt; constraint. &lt;/li&gt;    &lt;li&gt;Continue using &lt;em&gt;NUnit&lt;/em&gt; and &lt;em&gt;Visual Studio&lt;/em&gt; as they exist today, but include your own generic &lt;em&gt;Throws&lt;/em&gt; method in a support assembly that all your tests can use. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;If you have to go for the third option, here’s what I use for unit tests in &lt;em&gt;Visual Studio&lt;/em&gt;:&lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public static class&lt;/span&gt; &lt;span class="type"&gt;ExceptionAssert&lt;/span&gt;
{
  &lt;span class="kwrd"&gt;public static&lt;/span&gt; TException Throws&amp;lt;TException&amp;gt;(&lt;span class="type"&gt;Action&lt;/span&gt; action)
    &lt;span class="kwrd"&gt;where&lt;/span&gt; TException : &lt;span class="type"&gt;Exception&lt;/span&gt;
  {
    &lt;span class="type"&gt;Assert&lt;/span&gt;.IsNotNull(action, &lt;span class="str"&gt;&amp;quot;Argument 'action' cannot be a null reference.&amp;quot;&lt;/span&gt;);
    &lt;span class="type"&gt;Exception&lt;/span&gt; thrownException = &lt;span class="kwrd"&gt;null&lt;/span&gt;;
    &lt;span class="kwrd"&gt;try&lt;/span&gt;
    {
      action();
    }
    &lt;span class="kwrd"&gt;catch&lt;/span&gt; (&lt;span class="type"&gt;Exception&lt;/span&gt; ex)
    {
      thrownException = ex;
    }
    &lt;span class="kwrd"&gt;var&lt;/span&gt; expectedExceptionType = &lt;span class="kwrd"&gt;typeof&lt;/span&gt;(TException);
    &lt;span class="type"&gt;Assert&lt;/span&gt;.IsNotNull(
      thrownException,
      &lt;span class="str"&gt;&amp;quot;Expected an exception of type '{0}', but no exception was thrown.&amp;quot;&lt;/span&gt;,
      expectedExceptionType.FullName);
    &lt;span class="kwrd"&gt;var&lt;/span&gt; actualExceptionType = thrownException.GetType();
    &lt;span class="type"&gt;Assert&lt;/span&gt;.AreSame(
      expectedExceptionType,
      actualExceptionType,
      &lt;span class="str"&gt;&amp;quot;The thrown exception is not an instance of the expected exception type.&amp;quot;&lt;/span&gt;);
    &lt;span class="kwrd"&gt;return&lt;/span&gt; (TException)thrownException;
}&lt;/pre&gt;

&lt;p&gt;Adapting this to &lt;em&gt;NUnit&lt;/em&gt; should be straightforward as all you have to do is change the asserts to their &lt;em&gt;NUnit&lt;/em&gt; equivalents. Here’s an example of a test that uses this assert:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;[&lt;span class="type"&gt;TestMethod&lt;/span&gt;]
&lt;span class="kwrd"&gt;public void&lt;/span&gt; CopyConstructorWithExceptionForNullPrototype()
{
  &lt;span class="type"&gt;ArgumentNullException&lt;/span&gt; ex = &lt;span class="type"&gt;ExceptionAssert&lt;/span&gt;.Throws&amp;lt;&lt;span class="type"&gt;ArgumentNullException&lt;/span&gt;&amp;gt;(
    () =&amp;gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="type"&gt;MyClass&lt;/span&gt;(&lt;span class="kwrd"&gt;null&lt;/span&gt;));
  &lt;span class="type"&gt;Assert&lt;/span&gt;.AreEqual(
    &lt;span class="str"&gt;&amp;quot;prototype&amp;quot;&lt;/span&gt;, 
    ex.ParamName, 
    &lt;span class="str"&gt;&amp;quot;The exception identifies the wrong parameter name.&amp;quot;&lt;/span&gt;);
}&lt;/pre&gt;

&lt;p&gt;Returning the exception from the assert also allows us to verify whether or not the relevant properties have been set for the exception.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9201139154426574883-5502703287032806785?l=loadsofcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://loadsofcode.blogspot.com/feeds/5502703287032806785/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://loadsofcode.blogspot.com/2009/01/unit-testing-expected-exceptions.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/5502703287032806785'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/5502703287032806785'/><link rel='alternate' type='text/html' href='http://loadsofcode.blogspot.com/2009/01/unit-testing-expected-exceptions.html' title='Unit Testing Expected Exceptions'/><author><name>Kevin Westhead</name><uri>http://www.blogger.com/profile/05226243485559749240</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/-T93lAVSpKrI/Tu__lq-Ia9I/AAAAAAAAAII/tnKoAeDFrrs/s220/Kevin%2BWesthead%2B%2528grey%2529.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9201139154426574883.post-9151534679083565421</id><published>2009-01-22T23:00:00.001Z</published><updated>2009-01-23T18:25:32.194Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><category scheme='http://www.blogger.com/atom/ns#' term='Visual Studio'/><title type='text'>Beware of Unchecked Integer Arithmetic</title><content type='html'>&lt;p&gt;&lt;em&gt;C#&lt;/em&gt; provides the &lt;a href="http://msdn.microsoft.com/en-us/library/74b4xzyw.aspx"&gt;checked&lt;/a&gt; and &lt;a href="http://msdn.microsoft.com/en-us/library/a569z7k8.aspx"&gt;unchecked&lt;/a&gt; keywords to enable and disable overflow checking for integer arithmetic. It might surprise you to know that &lt;em&gt;Visual Studio C#&lt;/em&gt; projects disable overflow checking by default. Consider the following example:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;var&lt;/span&gt; a = &lt;span class="kwrd"&gt;int&lt;/span&gt;.MaxValue;
&lt;span class="type"&gt;Console&lt;/span&gt;.WriteLine(++a);&lt;/pre&gt;

&lt;p&gt;With the default project settings this code will output –2147483648 instead of throwing an &lt;a href="http://msdn.microsoft.com/en-us/library/system.overflowexception.aspx"&gt;OverflowException&lt;/a&gt;. Personally I think overflow checking should be enabled by default since overflow is rarely intentional and when it is, well that’s what the &lt;em&gt;unchecked&lt;/em&gt; keyword is for. Fortunately changing the default behaviour for &lt;em&gt;Visual Studio C#&lt;/em&gt; projects is straightforward. Open the project properties page, select the &lt;em&gt;Build&lt;/em&gt; tab and click the &lt;em&gt;Advanced…&lt;/em&gt; button.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://lh5.ggpht.com/_0dLBalBcXaI/SXKyHoIAKOI/AAAAAAAAABc/yFChidTSVLg/s1600-h/Checked%20Arithmetic%5B3%5D.png"&gt;&lt;img title="Advanced Build Settings Dialog" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="356" alt="Advanced Build Settings Dialog" src="http://lh4.ggpht.com/_0dLBalBcXaI/SXKyINA5USI/AAAAAAAAABg/vRjM1vFN3QU/Checked%20Arithmetic_thumb%5B1%5D.png?imgmax=800" width="477" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Check the &lt;em&gt;Check for arithmetic overflow/underflow&lt;/em&gt; check box in the resulting dialog as shown above. I’d recommend doing this for all of your build configurations.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9201139154426574883-9151534679083565421?l=loadsofcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://loadsofcode.blogspot.com/feeds/9151534679083565421/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://loadsofcode.blogspot.com/2009/01/beware-of-unchecked-integer-arithmetic.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/9151534679083565421'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/9151534679083565421'/><link rel='alternate' type='text/html' href='http://loadsofcode.blogspot.com/2009/01/beware-of-unchecked-integer-arithmetic.html' title='Beware of Unchecked Integer Arithmetic'/><author><name>Kevin Westhead</name><uri>http://www.blogger.com/profile/05226243485559749240</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/-T93lAVSpKrI/Tu__lq-Ia9I/AAAAAAAAAII/tnKoAeDFrrs/s220/Kevin%2BWesthead%2B%2528grey%2529.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://lh4.ggpht.com/_0dLBalBcXaI/SXKyINA5USI/AAAAAAAAABg/vRjM1vFN3QU/s72-c/Checked%20Arithmetic_thumb%5B1%5D.png?imgmax=800' height='72' width='72'/><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9201139154426574883.post-818993804427568470</id><published>2009-01-21T23:00:00.001Z</published><updated>2009-01-23T18:23:31.587Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><title type='text'>Exposing Collections Using a More Restricted Interface</title><content type='html'>&lt;p&gt;It’s quite reasonable to want to expose a collection as a property where the type of the property is a base type of the backing field. For example, the backing field for a collection property could be declared as &lt;a href="http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx"&gt;List&amp;lt;string&amp;gt;&lt;/a&gt; but the property itself could be declared as &lt;a href="http://msdn.microsoft.com/en-us/library/9eekhta0.aspx"&gt;IEnumerable&amp;lt;string&amp;gt;&lt;/a&gt;. This is useful when you need to modify the collection from within the type but don’t want clients to have the same freedom. You could implement this as follows:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public class&lt;/span&gt; &lt;span class="type"&gt;MyClass&lt;/span&gt;
{
  &lt;span class="kwrd"&gt;private readonly&lt;/span&gt; &lt;span class="type"&gt;List&lt;/span&gt;&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; m_items = &lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="type"&gt;List&lt;/span&gt;&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;();

  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="type"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; Items
  {
    &lt;span class="kwrd"&gt;get&lt;/span&gt; { &lt;span class="kwrd"&gt;return&lt;/span&gt; m_items; }
  }
}&lt;/pre&gt;

&lt;p&gt;Simple right? Unfortunately not. The problem here is that we’re still returning an instance of &lt;em&gt;List&amp;lt;string&amp;gt;&lt;/em&gt; even though we only expose it as &lt;em&gt;IEnumerable&amp;lt;string&amp;gt;&lt;/em&gt;. Callers can still cast the instance we returned to a more specialised type, which means they can modify the collection and generally wreak havoc. One way to address this is to return a proper read-only instance, such as &lt;a href="http://msdn.microsoft.com/en-us/library/ms132474.aspx"&gt;ReadOnlyCollection&amp;lt;string&amp;gt;&lt;/a&gt;.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public class&lt;/span&gt; &lt;span class="type"&gt;MyClass&lt;/span&gt;
{
  &lt;span class="kwrd"&gt;private readonly&lt;/span&gt; &lt;span class="type"&gt;List&lt;/span&gt;&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; m_items = &lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="type"&gt;List&lt;/span&gt;&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;();
  &lt;span class="kwrd"&gt;private readonly&lt;/span&gt; &lt;span class="type"&gt;ReadOnlyCollection&lt;/span&gt;&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; m_itemsReadOnly;

  &lt;span class="kwrd"&gt;public&lt;/span&gt; MyClass()
    : &lt;span class="kwrd"&gt;base&lt;/span&gt;()
  {
    m_itemsReadOnly = m_items.AsReadOnly();
  }

  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="type"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; Items
  {
    &lt;span class="kwrd"&gt;get&lt;/span&gt; { &lt;span class="kwrd"&gt;return&lt;/span&gt; m_itemsReadOnly; }
  }
}&lt;/pre&gt;

&lt;p&gt;Now if a caller casts the returned instance to a more specialised type, such as &lt;a href="http://msdn.microsoft.com/en-us/library/92t2ye13.aspx"&gt;ICollection&amp;lt;string&amp;gt;&lt;/a&gt;, any attempt to modify the collection will throw a &lt;a href="http://msdn.microsoft.com/en-us/library/system.notsupportedexception.aspx"&gt;NotSupportedException&lt;/a&gt; because the instance we returned is read-only. But why do we need a separate backing field for the read-only collection? Well the &lt;a href="http://www.amazon.co.uk/gp/product/0321545613?ie=UTF8&amp;amp;tag=lo60co62-21&amp;amp;linkCode=as2&amp;amp;camp=1634&amp;amp;creative=6738&amp;amp;creativeASIN=0321545613"&gt;Framework Design Guidelines&lt;/a&gt; states that properties should not return a different result each time they’re invoked. For reference types this means we should return the same instance. This makes sense when we consider that properties are generally expected to behave like fields but with some additional lightweight logic thrown in to the mix. In other words, we’d expect both of the following lines to evaluate to &lt;em&gt;true&lt;/em&gt;.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;m_value == m_value;       &lt;span class="rem"&gt;// Field equal to itself?&lt;/span&gt;
item.Value == item.Value; &lt;span class="rem"&gt;// Property equal to itself?&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;This means we can’t use the &lt;a href="http://msdn.microsoft.com/en-us/library/e78dcd75.aspx"&gt;AsReadOnly&lt;/a&gt; method in the property because it will return a different instance each time. We have to use a separate backing field for the read-only collection to achieve the expected behaviour for a property. We also don’t have to worry about updating this backing field when the collection changes because the &lt;em&gt;AsReadOnly&lt;/em&gt; method returns a wrapper around the original collection. Another approach I’ve seen is to use an &lt;a href="http://msdn.microsoft.com/en-us/library/dscyy5s0.aspx"&gt;iterator&lt;/a&gt; as shown below.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public class&lt;/span&gt; &lt;span class="type"&gt;MyClass&lt;/span&gt;
{
  &lt;span class="kwrd"&gt;private readonly&lt;/span&gt; &lt;span class="type"&gt;List&lt;/span&gt;&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; m_items = &lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="type"&gt;List&lt;/span&gt;&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;();

  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="type"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; Items
  {
    &lt;span class="kwrd"&gt;get&lt;/span&gt;
    {
      &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (&lt;span class="kwrd"&gt;string&lt;/span&gt; item &lt;span class="kwrd"&gt;in&lt;/span&gt; m_items)
      {
        &lt;span class="kwrd"&gt;yield return&lt;/span&gt; item;
      }
    }
  }
}&lt;/pre&gt;

&lt;p&gt;This works because the iterator will generate its own implementation of &lt;em&gt;IEnumerable&amp;lt;string&amp;gt;&lt;/em&gt; which is completely independent of the implementation provided by &lt;em&gt;List&amp;lt;string&amp;gt;&lt;/em&gt;. This means a caller cannot cast the returned instance to a more specialised type.&amp;#160; Unfortunately it will also return a different instance every time we access the property, which as we’ve already seen is not how properties should behave. So why not make it a method then? Well if the member represents a logical attribute of the type then it really should be a property. The &lt;em&gt;Items&lt;/em&gt; member seems to fit the bill, so a property is the right choice.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9201139154426574883-818993804427568470?l=loadsofcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://loadsofcode.blogspot.com/feeds/818993804427568470/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://loadsofcode.blogspot.com/2009/01/exposing-collections-using-more.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/818993804427568470'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/818993804427568470'/><link rel='alternate' type='text/html' href='http://loadsofcode.blogspot.com/2009/01/exposing-collections-using-more.html' title='Exposing Collections Using a More Restricted Interface'/><author><name>Kevin Westhead</name><uri>http://www.blogger.com/profile/05226243485559749240</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/-T93lAVSpKrI/Tu__lq-Ia9I/AAAAAAAAAII/tnKoAeDFrrs/s220/Kevin%2BWesthead%2B%2528grey%2529.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9201139154426574883.post-3481166317241341047</id><published>2009-01-20T23:00:00.001Z</published><updated>2009-01-23T18:20:27.529Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='Visual Studio'/><title type='text'>RIP Debug.WriteLine</title><content type='html'>&lt;p&gt;Not all developers using Visual Studio are aware of the fact that you can use breakpoints to write to the debug window. This saves you from having calls to &lt;a href="http://msdn.microsoft.com/en-gb/library/system.diagnostics.debug.writeline.aspx"&gt;Debug.WriteLine&lt;/a&gt; littered throughout your code, which you may not want to check-in. The reason for not checking-in &lt;em&gt;Debug.WriteLine&lt;/em&gt; calls is that it can clutter up the debug window for everyone working on the same source, making it hard for developers to pick out specific debug information they’ve added. Using a breakpoint allows you to keep the debug information local to your machine.&lt;/p&gt;

&lt;p&gt;To make a breakpoint that writes to the debug window, create a breakpoint as you normally would and right-click on it to bring up its context menu. Then select the &lt;em&gt;When Hit...&lt;/em&gt; menu item as shown below.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://lh6.ggpht.com/_0dLBalBcXaI/SXEaXBOsa4I/AAAAAAAAABA/suw_H691gWU/s1600-h/Create%20Breakpoint%5B59%5D.png"&gt;&lt;img title="Create a Breakpoint" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="227" alt="Create a Breakpoint" src="http://lh5.ggpht.com/_0dLBalBcXaI/SXEaXr6lpWI/AAAAAAAAABI/hQ1EKLVjjp8/Create%20Breakpoint_thumb%5B55%5D.png?imgmax=800" width="575" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Check the &lt;em&gt;Print a message:&lt;/em&gt; check box in the &lt;em&gt;When Breakpoint Is Hit&lt;/em&gt; dialog and enter the text you want written to the debug window.&amp;#160; In the screenshot below I’ve chosen to output the fully qualified method name followed by the value of the &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.propertychangedeventargs.propertyname.aspx"&gt;PropertyName&lt;/a&gt; property.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://lh5.ggpht.com/_0dLBalBcXaI/SXEaYB1T5fI/AAAAAAAAABM/ySmD4pPHuaY/s1600-h/When%20Hit%20Breakpoint%5B7%5D.png"&gt;&lt;img title="When Breakpoint is Hit Dialog" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="426" alt="When Breakpoint is Hit Dialog" src="http://lh3.ggpht.com/_0dLBalBcXaI/SXEaYaOElCI/AAAAAAAAABQ/rOMnxVVnbk8/When%20Hit%20Breakpoint_thumb%5B5%5D.png?imgmax=800" width="508" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Make sure the &lt;em&gt;Continue execution&lt;/em&gt; check box is checked to prevent the debugger from stopping at the breakpoint.&lt;/p&gt;

&lt;p&gt;You can also combine multiple items in the breakpoint context menu. For example, you can select the &lt;em&gt;Condition...&lt;/em&gt; menu item in addition to the &lt;em&gt;When Hit...&lt;/em&gt; menu item to write to the debug window only when a condition is either true or has changed.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://lh6.ggpht.com/_0dLBalBcXaI/SXEaYwg5hpI/AAAAAAAAABU/w06o1eQl14g/s1600-h/Condition%20Breakpoint%5B3%5D.png"&gt;&lt;img title="Breakpoint Condition Dialog" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="243" alt="Breakpoint Condition Dialog" src="http://lh5.ggpht.com/_0dLBalBcXaI/SXEaZIEvNFI/AAAAAAAAABY/AqqZvtDdjP8/Condition%20Breakpoint_thumb%5B1%5D.png?imgmax=800" width="508" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;All of this without having to make a single call to &lt;em&gt;Debug.WriteLine&lt;/em&gt;. May it rest in piece &lt;font face="Wingdings"&gt;J&lt;/font&gt;.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9201139154426574883-3481166317241341047?l=loadsofcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://loadsofcode.blogspot.com/feeds/3481166317241341047/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://loadsofcode.blogspot.com/2009/01/rip-debugwriteline.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/3481166317241341047'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/3481166317241341047'/><link rel='alternate' type='text/html' href='http://loadsofcode.blogspot.com/2009/01/rip-debugwriteline.html' title='RIP Debug.WriteLine'/><author><name>Kevin Westhead</name><uri>http://www.blogger.com/profile/05226243485559749240</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/-T93lAVSpKrI/Tu__lq-Ia9I/AAAAAAAAAII/tnKoAeDFrrs/s220/Kevin%2BWesthead%2B%2528grey%2529.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://lh5.ggpht.com/_0dLBalBcXaI/SXEaXr6lpWI/AAAAAAAAABI/hQ1EKLVjjp8/s72-c/Create%20Breakpoint_thumb%5B55%5D.png?imgmax=800' height='72' width='72'/><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9201139154426574883.post-8765859526237938337</id><published>2009-01-19T23:00:00.001Z</published><updated>2009-01-23T18:17:30.906Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><title type='text'>Operator Overloads vs. Methods</title><content type='html'>&lt;p&gt;It’s common practice for API designers providing operator overloads to follow the advice given in the &lt;a href="http://www.amazon.co.uk/gp/product/0321545613?ie=UTF8&amp;amp;tag=lo60co62-21&amp;amp;linkCode=as2&amp;amp;camp=1634&amp;amp;creative=6738&amp;amp;creativeASIN=0321545613"&gt;Framework Design Guidelines&lt;/a&gt;&lt;img style="margin: 0px; border-top-style: none! important; border-right-style: none! important; border-left-style: none! important; border-bottom-style: none! important" height="1" alt="" src="http://www.assoc-amazon.co.uk/e/ir?t=lo60co62-21&amp;amp;l=as2&amp;amp;o=2&amp;amp;a=0321545613" width="1" border="0" /&gt;and also provide methods with friendly names for the same operations. For example, the designers of the &lt;a href="http://msdn.microsoft.com/en-us/library/system.windows.media.media3d.vector3d.aspx"&gt;Vector3D&lt;/a&gt; structure provided a &lt;a href="http://msdn.microsoft.com/en-us/library/ms603889.aspx"&gt;Multiply&lt;/a&gt; method and a &lt;a href="http://msdn.microsoft.com/en-us/library/ms599648.aspx"&gt;Multiply&lt;/a&gt; operator to support multiplying a vector by a scalar. Why do they do this? Well, you can’t guarantee that all &lt;em&gt;.NET&lt;/em&gt; programming languages will support operator overloading because it is not part of the &lt;a href="http://msdn.microsoft.com/en-us/library/12a7a7h3.aspx"&gt;Common Language Specification&lt;/a&gt;. If you use &lt;em&gt;C#&lt;/em&gt;, which does support operator overloading, then you’re free to choose either the operators or the methods as there’s no difference between them, right? Well a problem I encountered recently made me stop and think about operator overloads, and how it can be difficult to keep track of the number of temporary objects being created. Consider the following snippet:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;private readonly&lt;/span&gt; &lt;span class="type"&gt;List&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;Point3D&lt;/span&gt;&amp;gt; m_points;
&lt;span class="kwrd"&gt;private readonly&lt;/span&gt; &lt;span class="type"&gt;List&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;Vector3D&lt;/span&gt;&amp;gt; m_velocities;

&lt;span class="kwrd"&gt;public void&lt;/span&gt; UpdatePoints(&lt;span class="kwrd"&gt;double&lt;/span&gt; variance, &lt;span class="kwrd"&gt;double&lt;/span&gt; ellapsedTime)
{
  &lt;span class="type"&gt;Debug&lt;/span&gt;.Assert(
    m_points.Count == m_velocities.Count, 
    &lt;span class="str"&gt;&amp;quot;Invalid collections.&amp;quot;&lt;/span&gt;, 
    &lt;span class="str"&gt;&amp;quot;Fields 'm_points' and 'm_velocities' should have equal counts.&amp;quot;&lt;/span&gt;);
  &lt;span class="kwrd"&gt;for&lt;/span&gt; (&lt;span class="kwrd"&gt;int&lt;/span&gt; i = 0; i &amp;lt; m_points.Count; i++)
  {
    m_points[i] -= m_velocities[i] * variance * ellapsedTime;
  }
}&lt;/pre&gt;

&lt;p&gt;How many &lt;em&gt;Vector3D&lt;/em&gt; objects are being created each time through the loop? Let's re-write the snippet to emphasise the temporary objects.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;private readonly&lt;/span&gt; &lt;span class="type"&gt;List&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;Point3D&lt;/span&gt;&amp;gt; m_points;
&lt;span class="kwrd"&gt;private readonly&lt;/span&gt; &lt;span class="type"&gt;List&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;Vector3D&lt;/span&gt;&amp;gt; m_velocities;

&lt;span class="kwrd"&gt;public void&lt;/span&gt; UpdatePoints(&lt;span class="kwrd"&gt;double&lt;/span&gt; variance, &lt;span class="kwrd"&gt;double&lt;/span&gt; ellapsedTime)
{
  &lt;span class="type"&gt;Debug&lt;/span&gt;.Assert(
    m_points.Count == m_velocities.Count, 
    &lt;span class="str"&gt;&amp;quot;Invalid collections.&amp;quot;&lt;/span&gt;, 
    &lt;span class="str"&gt;&amp;quot;Fields 'm_points' and 'm_velocities' should have equal counts.&amp;quot;&lt;/span&gt;);
  &lt;span class="kwrd"&gt;for&lt;/span&gt; (&lt;span class="kwrd"&gt;int&lt;/span&gt; i = 0; i &amp;lt; m_points.Count; i++)
  {
    &lt;span class="type"&gt;Vector3D&lt;/span&gt; tmp1 = vectors[i] * variance;
    &lt;span class="type"&gt;Vector3D&lt;/span&gt; tmp2 = tmp1 * ellapsedTime;
    m_points[i] -= tmp2;
  }
}&lt;/pre&gt;

&lt;p&gt;This makes it much easier to spot that two temporary &lt;em&gt;Vector3D&lt;/em&gt; objects are being created for the vector-scalar multiplications, i.e. one of them is unnecessary because we can combine the scalar values. Compare this with the original snippet re-written again to use the &lt;em&gt;Multiply&lt;/em&gt; method instead of the operator overload.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;private readonly&lt;/span&gt; &lt;span class="type"&gt;List&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;Point3D&lt;/span&gt;&amp;gt; m_points;
&lt;span class="kwrd"&gt;private readonly&lt;/span&gt; &lt;span class="type"&gt;List&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;Vector3D&lt;/span&gt;&amp;gt; m_velocities;

&lt;span class="kwrd"&gt;public void&lt;/span&gt; UpdatePoints(&lt;span class="kwrd"&gt;double&lt;/span&gt; variance, &lt;span class="kwrd"&gt;double&lt;/span&gt; ellapsedTime)
{
  &lt;span class="type"&gt;Debug&lt;/span&gt;.Assert(
    m_points.Count == m_velocities.Count, 
    &lt;span class="str"&gt;&amp;quot;Invalid collections.&amp;quot;&lt;/span&gt;, 
    &lt;span class="str"&gt;&amp;quot;Fields 'm_points' and 'm_velocities' should have equal counts.&amp;quot;&lt;/span&gt;);
  &lt;span class="kwrd"&gt;for&lt;/span&gt; (&lt;span class="kwrd"&gt;int&lt;/span&gt; i = 0; i &amp;lt; m_points.Count; i++)
  {
    m_points[i] -= &lt;span class="type"&gt;Vector3D&lt;/span&gt;.Multiply(
      &lt;span class="type"&gt;Vector3D&lt;/span&gt;.Multiply(m_velocities[i], variance), ellapsedTime);
  }
}&lt;/pre&gt;

&lt;p&gt;I think it's now obvious that we're performing two vector-scalar multiplications. In fact, had I used the &lt;em&gt;Multiply&lt;/em&gt; method initially I'm certain I would have automatically used only one &lt;em&gt;Multiply&lt;/em&gt; call as follows:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;private readonly&lt;/span&gt; &lt;span class="type"&gt;List&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;Point3D&lt;/span&gt;&amp;gt; m_points;
&lt;span class="kwrd"&gt;private readonly&lt;/span&gt; &lt;span class="type"&gt;List&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;Vector3D&lt;/span&gt;&amp;gt; m_velocities;

&lt;span class="kwrd"&gt;public void&lt;/span&gt; UpdatePoints(&lt;span class="kwrd"&gt;double&lt;/span&gt; variance, &lt;span class="kwrd"&gt;double&lt;/span&gt; ellapsedTime)
{
  &lt;span class="type"&gt;Debug&lt;/span&gt;.Assert(
    m_points.Count == m_velocities.Count, 
    &lt;span class="str"&gt;&amp;quot;Invalid collections.&amp;quot;&lt;/span&gt;, 
    &lt;span class="str"&gt;&amp;quot;Fields 'm_points' and 'm_velocities' should have equal counts.&amp;quot;&lt;/span&gt;);
  &lt;span class="kwrd"&gt;for&lt;/span&gt; (&lt;span class="kwrd"&gt;int&lt;/span&gt; i = 0; i &amp;lt; m_points.Count; i++)
  {
    m_points[i] -= &lt;span class="type"&gt;Vector3D&lt;/span&gt;.Multiply(m_velocities[i], variance * ellapsedTime);
  }
}&lt;/pre&gt;

&lt;p&gt;But is creating a few too many temporary &lt;em&gt;Vector3D&lt;/em&gt; objects that bad? Well in this scenario it depends on how many loops you perform and, even more importantly, what platform you're targeting. The impact for code running on desktops/servers will probably be negligible but I was certainly surprised by the difference these changes made on mobile/embedded devices. As a result I've begun to favour the clarity of methods over the terseness of operator overloads. There’s no guarantee that this will always provide any noticeable performance improvements but in my opinion the methods are closer to the &lt;a href="http://blogs.msdn.com/brada/archive/2005/10/07/478375.aspx"&gt;pit of success&lt;/a&gt; than the operator overloads. Note that the standard performance advice still applies, which is measure, measure, measure &lt;font face="Wingdings"&gt;J&lt;/font&gt;.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9201139154426574883-8765859526237938337?l=loadsofcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://loadsofcode.blogspot.com/feeds/8765859526237938337/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://loadsofcode.blogspot.com/2009/01/operator-overloads-vs-methods.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/8765859526237938337'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/8765859526237938337'/><link rel='alternate' type='text/html' href='http://loadsofcode.blogspot.com/2009/01/operator-overloads-vs-methods.html' title='Operator Overloads vs. Methods'/><author><name>Kevin Westhead</name><uri>http://www.blogger.com/profile/05226243485559749240</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/-T93lAVSpKrI/Tu__lq-Ia9I/AAAAAAAAAII/tnKoAeDFrrs/s220/Kevin%2BWesthead%2B%2528grey%2529.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9201139154426574883.post-7415643310269210642</id><published>2009-01-16T23:00:00.001Z</published><updated>2009-01-23T18:15:31.272Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='WPF'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><title type='text'>Better Freezing with Extension Methods</title><content type='html'>&lt;p&gt;You can improve the performance of &lt;a href="http://msdn.microsoft.com/en-us/library/system.windows.freezable.aspx"&gt;Freezable&lt;/a&gt; objects in &lt;em&gt;WPF&lt;/em&gt; by calling the &lt;a href="http://msdn.microsoft.com/en-us/library/ms557735.aspx"&gt;Freeze&lt;/a&gt; method. Frozen objects no longer need to be tracked by &lt;em&gt;WPF&lt;/em&gt; and the thread affinity associated with &lt;em&gt;WPF&lt;/em&gt; objects no longer applies. The documentation mentions a few cases where a &lt;em&gt;Freezable&lt;/em&gt; object cannot be frozen:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;It has animated or data bound properties.&lt;/li&gt;
  &lt;li&gt;It has properties that are set by a dynamic resource.&lt;/li&gt;
  &lt;li&gt;It contains &lt;em&gt;Freezable&lt;/em&gt; sub-objects that cannot be frozen.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If the &lt;em&gt;Freezable&lt;/em&gt; object cannot be frozen, the &lt;em&gt;Freeze&lt;/em&gt; method will throw an &lt;a href="http://msdn.microsoft.com/en-us/library/system.invalidoperationexception.aspx"&gt;InvalidOperationException&lt;/a&gt;. Unless you’re absolutely certain that the &lt;em&gt;Freeze&lt;/em&gt; method will always succeed, you should invoke it as follows:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;if&lt;/span&gt; (myFreezable.CanFreeze)
{
  myFreezable.Freeze();
}&lt;/pre&gt;

&lt;p&gt;Unfortunately the &lt;em&gt;Freezable&lt;/em&gt; object API does not provide a &lt;em&gt;TryFreeze&lt;/em&gt; method for scenarios when you don't care if the object can be frozen or not, i.e. you just want to freeze it whenever possible. You don’t really want the above code littered throughout your projects and a static helper method, while certainly better, may not be easily discovered even if it lives in a commonly imported namespace. I prefer to use the following extension method:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;internal static class&lt;/span&gt; &lt;span class="type"&gt;FreezableExtensionMethods
&lt;/span&gt;{
  &lt;span class="kwrd"&gt;public static void&lt;/span&gt; TryFreeze(&lt;span class="kwrd"&gt;this&lt;/span&gt; &lt;span class="type"&gt;Freezable&lt;/span&gt; freezable)
  {
    DebugVerifyFreezable(freezable);
    &lt;span class="kwrd"&gt;if&lt;/span&gt; (freezable.CanFreeze)
    {
      freezable.Freeze();
    }
  }

  [&lt;span class="type"&gt;Conditional&lt;/span&gt;(&lt;span class="str"&gt;&amp;quot;DEBUG&amp;quot;&lt;/span&gt;)]
  &lt;span class="kwrd"&gt;private static void&lt;/span&gt; DebugVerifyFreezable(&lt;span class="type"&gt;Freezable&lt;/span&gt; freezable)
  {
    &lt;span class="type"&gt;Debug&lt;/span&gt;.Assert(
      freezable != &lt;span class="kwrd"&gt;null&lt;/span&gt;, 
      &lt;span class="str"&gt;&amp;quot;Argument null.&amp;quot;&lt;/span&gt;, 
      &lt;span class="str"&gt;&amp;quot;Argument 'freezable' should not be null.&amp;quot;&lt;/span&gt;);
  }
}&lt;/pre&gt;

&lt;p&gt;Using &lt;a href="http://msdn.microsoft.com/en-gb/library/bb383977.aspx"&gt;extension methods&lt;/a&gt; in this way improves the discoverability of &lt;strong&gt;common&lt;/strong&gt; operations on types you don't own, assuming of course that they live in a frequently imported namespace. Note that I emphasised &lt;strong&gt;common&lt;/strong&gt; in the previous sentence because extension methods should not be used frivolously. The &lt;a href="http://www.amazon.co.uk/gp/product/0321545613?ie=UTF8&amp;amp;tag=lo60co62-21&amp;amp;linkCode=as2&amp;amp;camp=1634&amp;amp;creative=6738&amp;amp;creativeASIN=0321545613"&gt;Framework Design Guidelines&lt;/a&gt;&lt;img style="margin: 0px; border-top-style: none! important; border-right-style: none! important; border-left-style: none! important; border-bottom-style: none! important" height="1" alt="" src="http://www.assoc-amazon.co.uk/e/ir?t=lo60co62-21&amp;amp;l=as2&amp;amp;o=2&amp;amp;a=0321545613" width="1" border="0" /&gt;provides good advice about when to use extension methods. This advice is primarily intended for public APIs but in my opinion is equally valid for internal APIs.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9201139154426574883-7415643310269210642?l=loadsofcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://loadsofcode.blogspot.com/feeds/7415643310269210642/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://loadsofcode.blogspot.com/2009/01/better-freezing-with-extension-methods.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/7415643310269210642'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/7415643310269210642'/><link rel='alternate' type='text/html' href='http://loadsofcode.blogspot.com/2009/01/better-freezing-with-extension-methods.html' title='Better Freezing with Extension Methods'/><author><name>Kevin Westhead</name><uri>http://www.blogger.com/profile/05226243485559749240</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/-T93lAVSpKrI/Tu__lq-Ia9I/AAAAAAAAAII/tnKoAeDFrrs/s220/Kevin%2BWesthead%2B%2528grey%2529.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9201139154426574883.post-2835673785563073883</id><published>2009-01-14T23:36:00.001Z</published><updated>2009-01-23T18:12:53.326Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><title type='text'>Auto-Implemented Properties and Expressing Intent</title><content type='html'>&lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/bb384054.aspx"&gt;Auto-implemented properties&lt;/a&gt; provide a convenient way to quickly declare properties. This assumes of course that you don't need to run any logic, such as validation, in your property and that it is not read-only. Hang on, that last bit's wrong isn’t it? You can declare a read-only auto-implemented property as follows:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public bool&lt;/span&gt; IsReadOnly { &lt;span class="kwrd"&gt;get&lt;/span&gt;; &lt;span class="kwrd"&gt;private set&lt;/span&gt;; }&lt;/pre&gt;

&lt;p&gt;I see this quite a lot but I've got to be honest and say I'm not a big fan of using auto-implemented properties in this way. Why? Well it's only pretending to be a read-only property to the outside world. Internally the property could be modified after construction. If the intention is for the property to only be set during construction then this approach doesn’t fully reflect the intent. I’d always recommend writing code that most accurately expresses your intent, which in this case means a good old fashioned property with a read-only backing field.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;private readonly bool&lt;/span&gt; m_isReadOnly;

&lt;span class="kwrd"&gt;public bool&lt;/span&gt; IsReadOnly
{
  &lt;span class="kwrd"&gt;get&lt;/span&gt; { &lt;span class="kwrd"&gt;return&lt;/span&gt; m_isReadOnly; }
}&lt;/pre&gt;

&lt;p&gt;Implementing the property this way means any attempt to set the backing field after construction will be detected by the compiler. The more bugs the compiler can detect the better &lt;font face="Wingdings"&gt;J&lt;/font&gt;.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9201139154426574883-2835673785563073883?l=loadsofcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://loadsofcode.blogspot.com/feeds/2835673785563073883/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://loadsofcode.blogspot.com/2008/12/auto-implemented-properties-and.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/2835673785563073883'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/2835673785563073883'/><link rel='alternate' type='text/html' href='http://loadsofcode.blogspot.com/2008/12/auto-implemented-properties-and.html' title='Auto-Implemented Properties and Expressing Intent'/><author><name>Kevin Westhead</name><uri>http://www.blogger.com/profile/05226243485559749240</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/-T93lAVSpKrI/Tu__lq-Ia9I/AAAAAAAAAII/tnKoAeDFrrs/s220/Kevin%2BWesthead%2B%2528grey%2529.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-9201139154426574883.post-7250013062906099379</id><published>2008-12-22T20:37:00.008Z</published><updated>2009-01-23T18:11:22.824Z</updated><title type='text'>So Where's the Code?</title><content type='html'>&lt;p&gt;The code is coming &lt;span style="font-family:Wingdings;"&gt;J&lt;/span&gt;, but this blog won't officially start until 2009.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/9201139154426574883-7250013062906099379?l=loadsofcode.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://loadsofcode.blogspot.com/feeds/7250013062906099379/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://loadsofcode.blogspot.com/2008/12/so-wheres-code.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/7250013062906099379'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/9201139154426574883/posts/default/7250013062906099379'/><link rel='alternate' type='text/html' href='http://loadsofcode.blogspot.com/2008/12/so-wheres-code.html' title='So Where&amp;#39;s the Code?'/><author><name>Kevin Westhead</name><uri>http://www.blogger.com/profile/05226243485559749240</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/-T93lAVSpKrI/Tu__lq-Ia9I/AAAAAAAAAII/tnKoAeDFrrs/s220/Kevin%2BWesthead%2B%2528grey%2529.jpg'/></author><thr:total>0</thr:total></entry></feed>
