<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/atom10full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0" xml:lang="en" xml:base="http://www.pvle.be/wp-atom.php">
	<title type="text">Philippe</title>
	<subtitle type="text">I'm not that good but I'm not that bad</subtitle>

	<updated>2010-09-01T16:18:24Z</updated>
	<generator uri="http://wordpress.org/" version="2.9">WordPress</generator>

	<link rel="alternate" type="text/html" href="http://www.pvle.be" />
	<id>http://www.pvle.be/feed/atom/</id>
	

			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/atom+xml" href="http://feeds.feedburner.com/pvle" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="pvle" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><entry>
		<author>
			<name>Philippe</name>
						<uri>http://www.pvle.be</uri>
					</author>
		<title type="html"><![CDATA[Catching all Exceptions]]></title>
		<link rel="alternate" type="text/html" href="http://www.pvle.be/2010/09/catching-all-exceptions/" />
		<id>http://www.pvle.be/2010/09/catching-all-exceptions/</id>
		<updated>2010-09-01T16:18:24Z</updated>
		<published>2010-09-01T16:18:24Z</published>
		<category scheme="http://www.pvle.be" term="Uncategorized" />		<summary type="html"><![CDATA[These days, I&#8217;ve seen a lot of code like this in the code base I’m working on:
try
{
    //Do some parsing or any dangerous operation
}
catch (Exception)
{
    //Return something, as if nothing happened
}
Now, I can understand why this is done. It feels safe. After all, if you are in a method [...]]]></summary>
		<content type="html" xml:base="http://www.pvle.be/2010/09/catching-all-exceptions/"><![CDATA[<p>These days, I&#8217;ve seen a lot of code like this in the code base I’m working on:</p>
<pre class="code"><span style="color: blue">try
</span>{
    <span style="color: green">//Do some parsing or any dangerous operation
</span>}
<span style="color: blue">catch </span>(<span style="color: #2b91af">Exception</span>)
{
    <span style="color: green">//Return something, as if nothing happened
</span>}</pre>
<p>Now, I can understand why this is done. It feels <em>safe</em>. After all, if you are in a method that is supposed to return something, you can simply return a default value if an exception shows up, right?</p>
<p><em>Wrong. Very wrong.</em></p>
<p>Please, only catch the exceptions you know you can recover from. Let’s say you parse something in the try block. At first, check if there is a TryParse method to do that instead, so no exception is thrown in the first place. If that’s not an option, only catch the exceptions that are caused by the parsing process, not all exceptions.</p>
<p>Leave the exception you can’t deal with bubble up the calling hierarchy. At the end, the will reach a process that can handle them or that will fail and log them. That is the way to go in all situations.</p>
<p>For excellent references on exceptions guidelines, please see&#160; the excellent </p>
<p><a href="http://www.amazon.com/Framework-Design-Guidelines-Conventions-Libraries/dp/0321545613/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1283357789&amp;sr=8-1">Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries (2nd Edition)</a>.</p></p>
]]></content>
		<link rel="replies" type="text/html" href="http://www.pvle.be/2010/09/catching-all-exceptions/#comments" thr:count="0" />
		<link rel="replies" type="application/atom+xml" href="http://www.pvle.be/2010/09/catching-all-exceptions/feed/atom/" thr:count="0" />
		<thr:total>0</thr:total>
	</entry>
		<entry>
		<author>
			<name>Philippe</name>
						<uri>http://www.pvle.be</uri>
					</author>
		<title type="html"><![CDATA[SharePoint, SPWeb Objects and Dispose()]]></title>
		<link rel="alternate" type="text/html" href="http://www.pvle.be/2010/07/sharepoint-spweb-objects-and-dispose/" />
		<id>http://www.pvle.be/2010/07/sharepoint-spweb-objects-and-dispose/</id>
		<updated>2010-07-16T09:10:00Z</updated>
		<published>2010-07-16T09:10:00Z</published>
		<category scheme="http://www.pvle.be" term="Uncategorized" /><category scheme="http://www.pvle.be" term="Dispose" /><category scheme="http://www.pvle.be" term="SharePoint" />		<summary type="html"><![CDATA[If you worked a bit with SharePoint, you surely know how important it is to dispose of SPSite objects, SPWeb objects and such.
However, these objects are sometimes retrieved by using another object’s property. A very common one is SPContext.Current that has properties to return the current SPSite and SPWeb.
Needless to say, calling dispose on an [...]]]></summary>
		<content type="html" xml:base="http://www.pvle.be/2010/07/sharepoint-spweb-objects-and-dispose/"><![CDATA[<p>If you worked a bit with SharePoint, you surely know how important it is to dispose of SPSite objects, SPWeb objects and such.</p>
<p>However, these objects are sometimes retrieved by using another object’s property. A very common one is SPContext.Current that has properties to return the current SPSite and SPWeb.</p>
<p>Needless to say, calling dispose on an object that you got via another object’s property seems utterly rude. I mean, you are basically disposing something that was “borrowed” from another object. When I see code doing this, I get very suspicious.</p>
<p>Here is a common example:</p>
<pre class="code"><span style="color: blue">using </span>(<span style="color: #2b91af">SPWeb </span>web = <span style="color: #2b91af">SPContext</span>.Current.Web)
{
    <span style="color: green">//Do something with web
</span>}</pre>
<p>Using reflector, here is what SPContext.Web does:</p>
<pre class="code">public <a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://Microsoft.SharePoint:12.0.0.0:71e9bce111e9429c/Microsoft.SharePoint.SPWeb">SPWeb</a> <b><a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://Microsoft.SharePoint:12.0.0.0:71e9bce111e9429c/Microsoft.SharePoint.SPContext/property:Web:Microsoft.SharePoint.SPWeb">Web</a></b>
{
    get
    {
        if (this.<a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://Microsoft.SharePoint:12.0.0.0:71e9bce111e9429c/Microsoft.SharePoint.SPContext/m_web:Microsoft.SharePoint.SPWeb">m_web</a> == null)
        {
            this.<a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://Microsoft.SharePoint:12.0.0.0:71e9bce111e9429c/Microsoft.SharePoint.SPContext/m_web:Microsoft.SharePoint.SPWeb">m_web</a> = <a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://Microsoft.SharePoint:12.0.0.0:71e9bce111e9429c/Microsoft.SharePoint.WebControls.SPControl">SPControl</a>.<a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://Microsoft.SharePoint:12.0.0.0:71e9bce111e9429c/Microsoft.SharePoint.WebControls.SPControl/GetContextWeb(System.Web.HttpContext):Microsoft.SharePoint.SPWeb">GetContextWeb</a>(this.<a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://Microsoft.SharePoint:12.0.0.0:71e9bce111e9429c/Microsoft.SharePoint.SPContext/m_context:System.Web.HttpContext">m_context</a>);
        }
        return this.<a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://Microsoft.SharePoint:12.0.0.0:71e9bce111e9429c/Microsoft.SharePoint.SPContext/m_web:Microsoft.SharePoint.SPWeb">m_web</a>;
    }
}</pre>
<p>As we can see, this returns a private field of type SPWeb. Calling Dispose() on that (via the <em>using</em> statement) is clearly not very nice to our beloved SPContext. This kind of coding is known to bring unexpected errors. In fact, FxCop will raise a warning if it is set to check for SharePoint Best Practices Rules.</p>
<p>If this is a general rule, there are of course exceptions, I believe due to some inconsistencies in the API. Here is one of them:</p>
<pre class="code"><span style="color: #2b91af">SPWeb </span>web = <span style="color: #2b91af">SPContext</span>.Current.Web;

<span style="color: blue">foreach </span>(<span style="color: #2b91af">SPWeb </span>subWeb <span style="color: blue">in </span>web.Webs)
{
    <span style="color: green">//Do something with subWeb

    </span>subWeb.Dispose();
}</pre>
<p>In this particular case, we iterate over a collection of SPWeb objects trough the SPWeb.Webs property. As said before, at first sight, this looks bad. </p>
<p>Again, using reflector, this is what the Webs property does:</p>
<pre class="code">public <a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://Microsoft.SharePoint:12.0.0.0:71e9bce111e9429c/Microsoft.SharePoint.SPWebCollection">SPWebCollection</a> <b><a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://Microsoft.SharePoint:12.0.0.0:71e9bce111e9429c/Microsoft.SharePoint.SPWeb/property:Webs:Microsoft.SharePoint.SPWebCollection">Webs</a></b>
{
    get
    {
        if (this.<a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://Microsoft.SharePoint:12.0.0.0:71e9bce111e9429c/Microsoft.SharePoint.SPWeb/m_Webs:Microsoft.SharePoint.SPWebCollection">m_Webs</a> == null)
        {
            this.<a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://Microsoft.SharePoint:12.0.0.0:71e9bce111e9429c/Microsoft.SharePoint.SPWeb/m_Webs:Microsoft.SharePoint.SPWebCollection">m_Webs</a> = new <a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://Microsoft.SharePoint:12.0.0.0:71e9bce111e9429c/Microsoft.SharePoint.SPWebCollection/.ctor(Microsoft.SharePoint.SPWebCollection.ISPWebCollectionProvider,System.Guid)">SPWebCollection</a>(new <a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://Microsoft.SharePoint:12.0.0.0:71e9bce111e9429c/Microsoft.SharePoint.SPWeb.SPWebCollectionProvider/.ctor(Microsoft.SharePoint.SPWeb)">SPWebCollectionProvider</a>(this), this.<a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://Microsoft.SharePoint:12.0.0.0:71e9bce111e9429c/Microsoft.SharePoint.SPWeb/m_guidId:System.Guid">m_guidId</a>);
        }
        return this.<a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://Microsoft.SharePoint:12.0.0.0:71e9bce111e9429c/Microsoft.SharePoint.SPWeb/m_Webs:Microsoft.SharePoint.SPWebCollection">m_Webs</a>;
    }
}</pre>
<p>It is very similar to the previous code, so it feels very unnatural to call Dispose() on all object that are held in that collection.</p>
<p>However, this is the way to go, otherwise FxCop will raise a warning saying that SPWeb objects were not disposed of. In my opinion, this shouldn’t be a property, but a method called GetWebs() or something similar, as explained in <a href="http://msdn.microsoft.com/en-us/library/ms229054.aspx">Framework Design Guidelines</a>.</p>
<p>Related links:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/1237862/spweb-site-should-you-call-dispose-on-it">http://stackoverflow.com/questions/1237862/spweb-site-should-you-call-dispose-on-it</a> </li>
<li><a href="http://www.sharepointdevwiki.com/display/public/When+to+Dispose+SharePoint+objects">http://www.sharepointdevwiki.com/display/public/When+to+Dispose+SharePoint+objects</a> </li>
<li><a href="http://msdn.microsoft.com/en-us/library/aa973248.aspx">http://msdn.microsoft.com/en-us/library/aa973248.aspx</a> </li>
<li><a href="http://blogs.msdn.com/b/rogerla/archive/2008/02/12/sharepoint-2007-and-wss-3-0-dispose-patterns-by-example.aspx">http://blogs.msdn.com/b/rogerla/archive/2008/02/12/sharepoint-2007-and-wss-3-0-dispose-patterns-by-example.aspx</a> </li>
</ul>
]]></content>
		<link rel="replies" type="text/html" href="http://www.pvle.be/2010/07/sharepoint-spweb-objects-and-dispose/#comments" thr:count="0" />
		<link rel="replies" type="application/atom+xml" href="http://www.pvle.be/2010/07/sharepoint-spweb-objects-and-dispose/feed/atom/" thr:count="0" />
		<thr:total>0</thr:total>
	</entry>
		<entry>
		<author>
			<name>Philippe</name>
						<uri>http://www.pvle.be</uri>
					</author>
		<title type="html"><![CDATA[Instance Methods Called on null References]]></title>
		<link rel="alternate" type="text/html" href="http://www.pvle.be/2010/07/instance-methods-called-on-null-references/" />
		<id>http://www.pvle.be/2010/07/instance-methods-called-on-null-references/</id>
		<updated>2010-07-12T17:27:21Z</updated>
		<published>2010-07-12T17:27:21Z</published>
		<category scheme="http://www.pvle.be" term="Uncategorized" /><category scheme="http://www.pvle.be" term="C#" /><category scheme="http://www.pvle.be" term="call" /><category scheme="http://www.pvle.be" term="callvirt" /><category scheme="http://www.pvle.be" term="CLR" /><category scheme="http://www.pvle.be" term="IL" />		<summary type="html"><![CDATA[In a previous post, I wrote how you can call Extension Methods on null references, as in fact the are static methods with one more parameter, the extended object itself.
I’m currently reading CLR via C# (which is a fascinating read), and I was surprised to learn in chapter 6 how the CIL instructions call and [...]]]></summary>
		<content type="html" xml:base="http://www.pvle.be/2010/07/instance-methods-called-on-null-references/"><![CDATA[<p>In a <a href="http://www.pvle.be/2008/11/extension-methods-and-null-objects/">previous post</a>, I wrote how you can call Extension Methods on null references, as in fact the are static methods with one more parameter, the extended object itself.</p>
<p>I’m currently reading CLR via C# (which is a fascinating read), and I was surprised to learn in chapter 6 how the CIL instructions <em>call</em> and <em>callvirt</em> actually work.</p>
<p>What is amazing is that for methods called with the <em>call</em> instruction, the CLR does not check if the referenced object is null. The method call will succeed, but the <em>this</em> reference will be null in the instance method. Actually, in both cases, the reference to the object that the method was called on is passed as a hidden parameter to the method.</p>
<p>Before examining this, another interesting fact is the that the C# compiler mostly emits <em>callvirt</em> instructions when calling a method, which checks if the reference is null. To test the call instruction easily, we will have to disassemble, modify then reassemble the following code:</p>
<pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">SomeClass
</span>{
    <span style="color: blue">public </span><span style="color: #2b91af">String </span>GetHello()
    {
        <span style="color: blue">if </span>(<span style="color: blue">this </span>== <span style="color: blue">null</span>)
        {
            <span style="color: blue">return </span><span style="color: #a31515">&quot;Amazing!&quot;</span>;
        }

        <span style="color: blue">return </span><span style="color: #a31515">&quot;Hello&quot;</span>;
    }
}

<span style="color: blue">class </span><span style="color: #2b91af">Program
</span>{
    <span style="color: blue">static void </span>Main(<span style="color: blue">string</span>[] args)
    {
        <span style="color: blue">var </span>o = <span style="color: blue">null as </span><span style="color: #2b91af">SomeClass</span>;
        <span style="color: blue">var </span>hello = o.GetHello();

        <span style="color: #2b91af">Console</span>.WriteLine(hello);
    }
}</pre>
<p>Pretty dumb, right? Especially the if statement where we check if <em>this</em> is null. It’s seems logical to most of us that this will throw a NullReferenceException. However, this is just to get the compiler to build us code that is very close to what to achieve, so we don’t have to write IL ourselves.</p>
<p>After running <a href="http://msdn.microsoft.com/en-us/library/f7dy01k1(VS.80).aspx">ILDasm.exe</a> on the assembly, this is what we have in the Main method:</p>
<pre class="code">  .method private hidebysig static void  Main(string[] args) cil managed
  {
    .entrypoint
    // Code size       18 (0x12)
    .maxstack  1
    .locals init ([0] class Sandbox09.SomeClass o,
             [1] string hello)
    IL_0000:  nop
    IL_0001:  ldnull
    IL_0002:  stloc.0
    IL_0003:  ldloc.0
    IL_0004:  callvirt   instance string Sandbox09.SomeClass::GetHello()
    IL_0009:  stloc.1
    IL_000a:  ldloc.1
    IL_000b:  call       void [mscorlib]System.Console::WriteLine(string)
    IL_0010:  nop
    IL_0011:  ret
  } // end of method Program::Main</pre>
<p>As we can see, the call to GetHello is done with the <em>callvirt</em> instruction. As this instruction checks if the object is null (and in this case, it is), this will fail at runtime.</p>
<p>Just to make sure, I used <a href="http://msdn.microsoft.com/en-us/library/496e4ekx(VS.80).aspx">ILasm.exe</a> to build the assembly and ran it, here is what it outputs:</p>
<blockquote>
<p><em>Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.<br />
      <br />&#160;&#160; at Pvle.Program.Main(String[] args)</em></p>
</blockquote>
<p>Now, let’s try to replace the <em>callvirt</em> by <em>call</em> to see how it behaves.</p>
<pre class="code">    IL_0004:  call       instance string Sandbox09.SomeClass::GetHello()</pre>
<p>Now, run it again trough <a href="http://msdn.microsoft.com/en-us/library/496e4ekx(VS.80).aspx">ILasm.exe</a> once more and run it. Here’s what it outputs:</p>
<blockquote>
<p>Amazing!</p>
</blockquote>
<p>The actual difference between <em>call</em> and <em>callvirt</em> is that <em>call</em> calls the method on the compile time type of the object, so there is no need to check if the reference is null. The object will be passed as a hidden parameter to the method and will be references as <em>this</em>. It’s very similar to extension methods.</p>
<p><em>Callvirt</em>, on the other hand, will resolve the method that is to be called at runtime, depending on the runtime type of the object, so the object cannot be null. The CLR enforces this check at runtime.</p>
<h3>What About Value Types?</h3>
<p>For value types, it’s a bit different. As they are implicitly sealed, the only methods that are virtual are the ones that are defined in <a href="http://msdn.microsoft.com/en-us/library/system.object.aspx">System.Object</a>. Oh wait, there is another case: if the value type is cast to an interface it implements, calls to methods on that variable will be using <em>callvirt</em>, as the value type will have to be boxed.</p>
<p>Here is some sample code that demonstrates this:</p>
<pre class="code"><span style="color: blue">public interface </span><span style="color: #2b91af">ISomeInterface
</span>{
    <span style="color: #2b91af">String </span>GetHelloFromInterface();
}

<span style="color: blue">public struct </span><span style="color: #2b91af">SomeClass </span>: <span style="color: #2b91af">ISomeInterface
</span>{
    <span style="color: blue">public </span><span style="color: #2b91af">String </span>GetHello()
    {
        <span style="color: blue">return </span><span style="color: #a31515">&quot;Hello&quot;</span>;
    }

    <span style="color: blue">public override string </span>ToString()
    {
        <span style="color: blue">return </span><span style="color: #a31515">&quot;Hello&quot;</span>;
    }

    <span style="color: blue">public </span><span style="color: #2b91af">String </span>GetHelloFromInterface()
    {
        <span style="color: blue">return </span><span style="color: #a31515">&quot;Hello from interface&quot;</span>;
    }
}

<span style="color: blue">class </span><span style="color: #2b91af">Program
</span>{
    <span style="color: blue">static void </span>Main(<span style="color: blue">string</span>[] args)
    {
        <span style="color: blue">var </span>o = <span style="color: blue">new </span><span style="color: #2b91af">SomeClass</span>();
        <span style="color: blue">var </span>hello = o.GetHello();

        o.ToString();
        o.GetHelloFromInterface();
        ((<span style="color: #2b91af">ISomeInterface</span>)o).GetHelloFromInterface();
        o.GetHashCode();
    }
}</pre>
<p>And here is the corresponding IL for the Main method:</p>
<pre class="code">  .method private hidebysig static void  Main(string[] args) cil managed
  {
    .entrypoint
    // Code size       66 (0x42)
    .maxstack  1
    .locals init ([0] valuetype Pvle.SomeClass o,
             [1] string hello)
    IL_0000:  nop
    IL_0001:  ldloca.s   o
    IL_0003:  initobj    Pvle.SomeClass
    IL_0009:  ldloca.s   o
    IL_000b:  call       instance string Pvle.SomeClass::GetHello()
    IL_0010:  stloc.1
    IL_0011:  ldloca.s   o
    IL_0013:  constrained. Pvle.SomeClass
    IL_0019:  callvirt   instance string [mscorlib]System.Object::ToString()
    IL_001e:  pop
    IL_001f:  ldloca.s   o
    IL_0021:  call       instance string Pvle.SomeClass::GetHelloFromInterface()
    IL_0026:  pop
    IL_0027:  ldloc.0
    IL_0028:  box        Pvle.SomeClass
    IL_002d:  callvirt   instance string Pvle.ISomeInterface::GetHelloFromInterface()
    IL_0032:  pop
    IL_0033:  ldloca.s   o
    IL_0035:  constrained. Pvle.SomeClass
    IL_003b:  callvirt   instance int32 [mscorlib]System.Object::GetHashCode()
    IL_0040:  pop
    IL_0041:  ret
  } // end of method Program::Main</pre>
<p>We can see that when calling the method trough the interface, the value type is boxed.</p>
<p>I find this very interesting in understanding how calls to methods actually work. Getting your nose in IL is always a good idea when you want to see what happening under the hood, but I have to admit that this is the first time that I modify it and reassemble it.</p>
]]></content>
		<link rel="replies" type="text/html" href="http://www.pvle.be/2010/07/instance-methods-called-on-null-references/#comments" thr:count="0" />
		<link rel="replies" type="application/atom+xml" href="http://www.pvle.be/2010/07/instance-methods-called-on-null-references/feed/atom/" thr:count="0" />
		<thr:total>0</thr:total>
	</entry>
		<entry>
		<author>
			<name>Philippe</name>
						<uri>http://www.pvle.be</uri>
					</author>
		<title type="html"><![CDATA[SelectMany, Sorting and Grouping Objects]]></title>
		<link rel="alternate" type="text/html" href="http://www.pvle.be/2010/07/sorting-and-grouping-objects/" />
		<id>http://www.pvle.be/2010/07/sorting-and-grouping-objects/</id>
		<updated>2010-07-02T15:16:06Z</updated>
		<published>2010-07-02T15:14:30Z</published>
		<category scheme="http://www.pvle.be" term="Uncategorized" /><category scheme="http://www.pvle.be" term="C#" /><category scheme="http://www.pvle.be" term="LINQ" />		<summary type="html"><![CDATA[So here is the problem: I have a list of items that 
var collection = new[]
{
    new { Title = &#34;One&#34;, References = &#34;1;3&#34; },
    new { Title = &#34;Two&#34;, References = &#34;2;3&#34; },
    new { Title = &#34;Three&#34;, References = &#34;1;4&#34; },
    [...]]]></summary>
		<content type="html" xml:base="http://www.pvle.be/2010/07/sorting-and-grouping-objects/"><![CDATA[<p>So here is the problem: I have a list of items that </p>
<pre class="code"><span style="color: blue">var </span>collection = <span style="color: blue">new</span>[]
{
    <span style="color: blue">new </span>{ Title = <span style="color: #a31515">&quot;One&quot;</span>, References = <span style="color: #a31515">&quot;1;3&quot; </span>},
    <span style="color: blue">new </span>{ Title = <span style="color: #a31515">&quot;Two&quot;</span>, References = <span style="color: #a31515">&quot;2;3&quot; </span>},
    <span style="color: blue">new </span>{ Title = <span style="color: #a31515">&quot;Three&quot;</span>, References = <span style="color: #a31515">&quot;1;4&quot; </span>},
    <span style="color: blue">new </span>{ Title = <span style="color: #a31515">&quot;Four&quot;</span>, References = <span style="color: #a31515">&quot;4&quot;</span>}
};</pre>
<p>The <em>References</em> fields of these object is some kind of category. What I want to do here is to have a list for each different reference (in this example: 1, 2, 3 and 4) containing all the items that are in the reference. Items will be duplicated if they are in more than one category.</p>
<p>To sum it up, the expected output would be: One, Three, Two, One, Two, Three, Four</p>
<p>After fooling around a bit, here is the query I came out with:</p>
<pre class="code"><span style="color: blue">var </span>query = <span style="color: blue">from </span>c <span style="color: blue">in </span>collection
            <span style="color: blue">from </span>d <span style="color: blue">in </span>c.References.Split(<span style="color: #a31515">';'</span>)
            <span style="color: blue">orderby </span>d
            <span style="color: blue">group </span>c <span style="color: blue">by </span>d <span style="color: blue">into </span>groups
            <span style="color: blue">select </span>groups;</pre>
<p>This does exactly what I want and produces the output I expected from the input data.</p>
<p>However, when I use Linq, I generally use extensions methods directly and not the pretty query syntax. This is mostly because I want to understand what happens behind the scene, and I have to admit that this query was quite a beast.</p>
<p>First, as there are two <em>from</em> clauses, there is a <em>SelectMany</em> somewhere. You probably know that <em>SelectMany</em> is a kind of the beast and that understanding it fully is quite a challenge compared to the other operators/extensions methods. Also, I thought that the <em>GroupBy</em> clause was going to be tough, as we groups <em>c</em> items by <em>d</em> which is in the other collection.</p>
<p>I couldn’t figure out by myself how to write that query using extension methods, so I fell back on the good old Reflector that gave me a straight answer:</p>
<pre class="code">var query = collection.SelectMany(delegate (&lt;&gt;f__AnonymousType0<string string ,> c) {
    return c.Values.Split(new char[] { ';' });
}, delegate (&lt;&gt;f__AnonymousType0<string string ,> c, string d) {
    return new { c = c, d = d };
}).OrderBy(delegate (&lt;&gt;f__AnonymousType1&lt;&lt;&gt;f__AnonymousType0<string string ,>, string&gt; &lt;&gt;h__TransparentIdentifier0) {
    return &lt;&gt;h__TransparentIdentifier0.d;
}).GroupBy(delegate (&lt;&gt;f__AnonymousType1&lt;&lt;&gt;f__AnonymousType0<string string ,>, string&gt; &lt;&gt;h__TransparentIdentifier0) {
    return &lt;&gt;h__TransparentIdentifier0.d;
}, delegate (&lt;&gt;f__AnonymousType1&lt;&lt;&gt;f__AnonymousType0<string string ,>, string&gt; &lt;&gt;h__TransparentIdentifier0) {
    return &lt;&gt;h__TransparentIdentifier0.c;
}).Select(delegate (IGrouping<string   ,>&lt;&gt;f__AnonymousType0<string string ,>&gt; groups) {
    return groups;
});</pre>
<p>After reading that, it made much more sense. Here is what I came up with when writing it on my own:</p>
<pre class="code"><span style="color: blue">var </span>p = collection
    .SelectMany(c =&gt; c.References.Split(<span style="color: #a31515">';'</span>), (c, d) =&gt; <span style="color: blue">new </span>{ c, d })
    .OrderBy(t =&gt; t.d)
    .GroupBy(t =&gt; t.d, c =&gt; c.c);</pre>
<p>Much more readable. The idea here is that the <em>SelectMany</em> clause outputs a sequence of anonymous types that contains the two kind of elements. This sequence is then sorted with the <em>OrderBy</em>, and finally fed trough a <em>GroupBy</em> that uses the <em>d</em> property as the grouping key and the <em>c</em> property as the project in the resulting collections. Not that difficult after all…</p>
<p>Here is another version that is probably a bit more clear:</p>
<pre class="code"><span style="color: blue">var </span>q = collection
    .SelectMany(c =&gt; c.References.Split(<span style="color: #a31515">';'</span>), (c, d) =&gt; <span style="color: blue">new </span>{ Title = c.Title, Reference = d })
    .GroupBy(c =&gt; c.Reference, c =&gt; c.Title)
    .OrderBy(g =&gt; g.Key);</pre>
<p>Note that this is a simplified version of the original issue. The issue itself was to do this with some <em>ListItems</em> retrieved from SharePoint. Objects were a bit more complicated, but logic is the same.</p>
]]></content>
		<link rel="replies" type="text/html" href="http://www.pvle.be/2010/07/sorting-and-grouping-objects/#comments" thr:count="0" />
		<link rel="replies" type="application/atom+xml" href="http://www.pvle.be/2010/07/sorting-and-grouping-objects/feed/atom/" thr:count="0" />
		<thr:total>0</thr:total>
	</entry>
		<entry>
		<author>
			<name>Philippe</name>
						<uri>http://www.pvle.be</uri>
					</author>
		<title type="html"><![CDATA[Double check locking Extension Method for ASP.NET Cache]]></title>
		<link rel="alternate" type="text/html" href="http://www.pvle.be/2010/06/double-check-locking-extension-method-for-asp-net-cache/" />
		<id>http://www.pvle.be/2010/06/double-check-locking-extension-method-for-asp-net-cache/</id>
		<updated>2010-06-22T11:26:47Z</updated>
		<published>2010-06-22T11:26:47Z</published>
		<category scheme="http://www.pvle.be" term="Uncategorized" /><category scheme="http://www.pvle.be" term="ASP.NET" /><category scheme="http://www.pvle.be" term="C#" /><category scheme="http://www.pvle.be" term="Caching" /><category scheme="http://www.pvle.be" term="SharePoint" />		<summary type="html"><![CDATA[On my current project, we need to cache some of the results retreived when querying into SharePoint. As the retrieving operation is quite expensive (as always with SharePoint) and that performances are very important, we must make sure that it is only executed once.
So, the way to do this is to use the double check [...]]]></summary>
		<content type="html" xml:base="http://www.pvle.be/2010/06/double-check-locking-extension-method-for-asp-net-cache/"><![CDATA[<p>On my current project, we need to cache some of the results retreived when querying into SharePoint. As the retrieving operation is quite expensive (as always with SharePoint) and that performances are very important, we must make sure that it is only executed once.</p>
<p>So, the way to do this is to use the double check locking mechanism. The idea is to check if the cache contains the item sought, if it does not contain it, lock then check again, in case another thread added it while we were acquiring the lock.</p>
<p>I wrote a generic extension method to do this, to which the lock handle to lock on is given as a parameter, as well as the function used to retrieve the item if it is not in the cache. In this case, the retrieved item will be stored in the cache (and of course returned to the called).</p>
<p>Code speaks louder than words:</p>
<pre class="code"><span style="color: blue">public static class </span><span style="color: #2b91af">CacheExtension
</span>{
    <span style="color: blue">public static </span>T SetAndGetItemFromCache&lt;T&gt;(<span style="color: blue">this </span><span style="color: #2b91af">Cache </span>cache, <span style="color: #2b91af">String </span>cacheKey, <span style="color: #2b91af">Object </span>lockHandle, <span style="color: #2b91af">Func</span>&lt;<span style="color: #2b91af">Cache</span>, T&gt; addItemToCache)
    {
        <span style="color: #2b91af">Object </span>item = cache.Get(cacheKey);

        <span style="color: blue">if </span>(item == <span style="color: blue">null</span>)
        {
            <span style="color: blue">lock </span>(lockHandle)
            {
                item = cache.Get(cacheKey);

                <span style="color: blue">if </span>(item == <span style="color: blue">null</span>)
                {
                    item = addItemToCache(cache);
                }
                <span style="color: blue">else
                </span>{
                    <span style="color: green">//The sought item has been added meanwhile in another thread/process
                </span>}
            }
        }
        <span style="color: blue">else
        </span>{
            <span style="color: green">//Cache contains the key, return it
        </span>}

        <span style="color: blue">if </span>(item <span style="color: blue">is </span>T)
        {
            <span style="color: blue">return </span>(T)item;
        }
        <span style="color: blue">else
        </span>{
            <span style="color: green">//The Object in the cache is not of type T, some other component might be using that key
             </span><span style="color: blue">throw new </span><span style="color: #2b91af">ApplicationException</span>(<span style="color: #2b91af">String</span>.Format(<span style="color: #a31515">&quot;Object retreived from the cache is not of the expected {0} type. Another component might be using the same key to store in the cache.&quot;</span>, <span style="color: blue">typeof</span>(T).FullName));
        }
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>This can be used on any <a href="http://msdn.microsoft.com/en-us/library/system.web.caching.cache.aspx">System.Web.Caching.Cache</a> object.</p>
]]></content>
		<link rel="replies" type="text/html" href="http://www.pvle.be/2010/06/double-check-locking-extension-method-for-asp-net-cache/#comments" thr:count="1" />
		<link rel="replies" type="application/atom+xml" href="http://www.pvle.be/2010/06/double-check-locking-extension-method-for-asp-net-cache/feed/atom/" thr:count="1" />
		<thr:total>1</thr:total>
	</entry>
		<entry>
		<author>
			<name>Philippe</name>
						<uri>http://www.pvle.be</uri>
					</author>
		<title type="html"><![CDATA[Foreach Statement Calls Dispose() on IEnumerator]]></title>
		<link rel="alternate" type="text/html" href="http://www.pvle.be/2010/05/foreach-statement-calls-dispose-on-ienumerator/" />
		<id>http://www.pvle.be/2010/05/foreach-statement-calls-dispose-on-ienumerator/</id>
		<updated>2010-05-30T15:06:29Z</updated>
		<published>2010-05-30T15:06:29Z</published>
		<category scheme="http://www.pvle.be" term="Uncategorized" /><category scheme="http://www.pvle.be" term="C#" />		<summary type="html"><![CDATA[Again, something that might seems natural because you generally don’t see it or even think about it, but interesting to know.
If the IEnumerator/IEnumerator&#60;T&#62; returned by the GetEnumerator() function of a collection that is foreach-ed implements IDisposable, Dispose() will be called on it when the foreach is over.
Here is a sample code that does just that:
class [...]]]></summary>
		<content type="html" xml:base="http://www.pvle.be/2010/05/foreach-statement-calls-dispose-on-ienumerator/"><![CDATA[<p>Again, something that might seems natural because you generally don’t see it or even think about it, but interesting to know.</p>
<p>If the <a href="http://msdn.microsoft.com/en-us/library/system.collections.ienumerator.aspx"><em>IEnumerator</em></a>/<a href="http://msdn.microsoft.com/en-us/library/78dfe2yb.aspx"><em>IEnumerator&lt;T&gt;</em></a> returned by the <a href="http://msdn.microsoft.com/en-us/library/s793z9y2(v=VS.100).aspx"><em>GetEnumerator()</em></a> function of a collection that is foreach-ed implements <em><a href="http://msdn.microsoft.com/en-us/library/system.idisposable.aspx">IDisposable</a></em>, <em><a href="http://msdn.microsoft.com/en-us/library/system.idisposable.dispose(v=VS.100).aspx">Dispose()</a></em> will be called on it when the <a href="http://msdn.microsoft.com/en-us/library/aa664754(VS.71).aspx"><em>foreach</em></a> is over.</p>
<p>Here is a sample code that does just that:</p>
<pre class="code"><span style="color: blue">class </span><span style="color: #2b91af">Program
    </span>{
        <span style="color: blue">static void </span>Main(<span style="color: blue">string</span>[] args)
        {
            <span style="color: blue">foreach </span>(<span style="color: blue">var </span>item <span style="color: blue">in new </span><span style="color: #2b91af">SomeEnumerable</span>())
            {
                <span style="color: #2b91af">Console</span>.WriteLine(item);
            }

            <span style="color: #2b91af">Console</span>.ReadLine();
        }

        <span style="color: blue">class </span><span style="color: #2b91af">SomeEnumerable </span>: <span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: #2b91af">String</span>&gt;
        {
            <span style="color: blue">#region </span>IEnumerable&lt;string&gt; Members

            <span style="color: blue">public </span><span style="color: #2b91af">IEnumerator</span>&lt;<span style="color: #2b91af">String</span>&gt; GetEnumerator()
            {
                <span style="color: blue">return new </span><span style="color: #2b91af">CustomEnumerator</span>(<span style="color: blue">new </span><span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">String</span>&gt;() { <span style="color: #a31515">&quot;One&quot;</span>, <span style="color: #a31515">&quot;Two&quot; </span>}.GetEnumerator());
            }

            <span style="color: blue">#endregion

            #region </span>IEnumerable Members

            System.Collections.<span style="color: #2b91af">IEnumerator </span>System.Collections.<span style="color: #2b91af">IEnumerable</span>.GetEnumerator()
            {
                <span style="color: blue">return </span>GetEnumerator();
            }

            <span style="color: blue">#endregion

            class </span><span style="color: #2b91af">CustomEnumerator </span>: <span style="color: #2b91af">IEnumerator</span>&lt;<span style="color: #2b91af">String</span>&gt;
            {
                <span style="color: #2b91af">IEnumerator</span>&lt;<span style="color: #2b91af">String</span>&gt; enumerator;

                <span style="color: blue">public </span>CustomEnumerator(<span style="color: #2b91af">IEnumerator</span>&lt;<span style="color: #2b91af">String</span>&gt; enumerator)
                {
                    <span style="color: blue">this</span>.enumerator = enumerator;
                }

                <span style="color: blue">#region </span>IEnumerator&lt;string&gt; Members

                <span style="color: blue">public string </span>Current
                {
                    <span style="color: blue">get </span>{ <span style="color: blue">return this</span>.enumerator.Current; }
                }

                <span style="color: blue">#endregion

                #region </span>IDisposable Members

                <span style="color: blue">public void </span>Dispose()
                {
                    <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">&quot;SomeEnumerable Enumerator Disposed!&quot;</span>);

                    <span style="color: blue">this</span>.enumerator.Dispose();
                }

                <span style="color: blue">#endregion

                #region </span>IEnumerator Members

                <span style="color: blue">object </span>System.Collections.<span style="color: #2b91af">IEnumerator</span>.Current
                {
                    <span style="color: blue">get </span>{ <span style="color: blue">return this</span>.enumerator.Current; }
                }

                <span style="color: blue">public bool </span>MoveNext()
                {
                    <span style="color: blue">return this</span>.enumerator.MoveNext();
                }

                <span style="color: blue">public void </span>Reset()
                {
                    <span style="color: blue">this</span>.enumerator.Reset();
                }

                <span style="color: blue">#endregion
            </span>}
        }
    }</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>You can look at the two possible code expansions for the <em>foreach</em> statement on <a href="http://msdn.microsoft.com/en-us/library/aa664754(VS.71).aspx">the MSDN page</a>.</p>
]]></content>
		<link rel="replies" type="text/html" href="http://www.pvle.be/2010/05/foreach-statement-calls-dispose-on-ienumerator/#comments" thr:count="0" />
		<link rel="replies" type="application/atom+xml" href="http://www.pvle.be/2010/05/foreach-statement-calls-dispose-on-ienumerator/feed/atom/" thr:count="0" />
		<thr:total>0</thr:total>
	</entry>
		<entry>
		<author>
			<name>Philippe</name>
						<uri>http://www.pvle.be</uri>
					</author>
		<title type="html"><![CDATA[Using Statement with an &#8220;expression&#8221;]]></title>
		<link rel="alternate" type="text/html" href="http://www.pvle.be/2010/05/using-statement-with-an-expression/" />
		<id>http://www.pvle.be/2010/05/using-statement-with-an-expression/</id>
		<updated>2010-05-24T18:08:28Z</updated>
		<published>2010-05-24T18:08:28Z</published>
		<category scheme="http://www.pvle.be" term="Uncategorized" /><category scheme="http://www.pvle.be" term="C#" /><category scheme="http://www.pvle.be" term="Using Statement" />		<summary type="html"><![CDATA[Reading More Effective C# book, I was amazed to find out that the using statement can be used simply with an expression:
using-statement:      using ( resource-acquisition ) embedded-statement
resource-acquisition:      local-variable-declaration      expression

If the resource-acquisition is an expression, the variable resulting from the expression [...]]]></summary>
		<content type="html" xml:base="http://www.pvle.be/2010/05/using-statement-with-an-expression/"><![CDATA[<p>Reading <a href="http://www.amazon.com/exec/obidos/ASIN/0321485890/chaymart02-20">More Effective C#</a> book, I was amazed to find out that the <em>using</em> statement can be used simply with an expression:</p>
<blockquote><p><em>using-statement:</em>      <br />using ( <em>resource-acquisition</em> ) <em>embedded-statement</em></p>
<p><em>resource-acquisition:</em>      <br /><em>local-variable-declaration</em>      <br /><em>expression</em></p>
</blockquote>
<p>If the <em>resource-acquisition</em> is an <em>expression</em>, the variable resulting from the expression will be <em>inaccessible</em> to the <em>embedded-statement</em>.</p>
<p>Now, the reason why this is outlined in Bill Wagner’s book is when you write generic classes. Simply put, if <em>expression</em> is something like “a as IDisposable”, if a actually implements <a href="http://msdn.microsoft.com/en-us/library/system.idisposable.aspx"><em>IDisposable</em></a>, it will be disposed after the using statement. If it does not implements <em>IDisposable</em>, nothing will happen.</p>
<p>The beauty of this is that you don’t have to know, it will work in all cases.</p>
<p>I didn’t know that, and I find it very neat!</p>
]]></content>
		<link rel="replies" type="text/html" href="http://www.pvle.be/2010/05/using-statement-with-an-expression/#comments" thr:count="0" />
		<link rel="replies" type="application/atom+xml" href="http://www.pvle.be/2010/05/using-statement-with-an-expression/feed/atom/" thr:count="0" />
		<thr:total>0</thr:total>
	</entry>
		<entry>
		<author>
			<name>Philippe</name>
						<uri>http://www.pvle.be</uri>
					</author>
		<title type="html"><![CDATA[Getting an Assembly&#8217;s Strong name with PowerShell]]></title>
		<link rel="alternate" type="text/html" href="http://www.pvle.be/2010/04/getting-an-assemblys-strong-name-with-powershell/" />
		<id>http://www.pvle.be/2010/04/getting-an-assemblys-strong-name-with-powershell/</id>
		<updated>2010-04-21T20:29:53Z</updated>
		<published>2010-04-21T20:29:53Z</published>
		<category scheme="http://www.pvle.be" term="Uncategorized" /><category scheme="http://www.pvle.be" term="PowerShell" />		<summary type="html"><![CDATA[Quick tip, should get me out of blogging hibernation.
It’s a common issue to find an assembly’s strong name, but this can be done very easily with a simple PowerShell function:

function Get-AssemblyStrongName&#40;$assemblyPath&#41;
&#123;
	&#91;System.Reflection.AssemblyName&#93;::GetAssemblyName&#40;$assemblyPath&#41;.FullName
&#125;

Simply give the assembly&#8217;s full path and you&#8217;ll get the strong name in return.
Personnaly, I have that in my $profile file and have an alias [...]]]></summary>
		<content type="html" xml:base="http://www.pvle.be/2010/04/getting-an-assemblys-strong-name-with-powershell/"><![CDATA[<p>Quick tip, should get me out of blogging hibernation.</p>
<p>It’s a common issue to find an assembly’s strong name, but this can be done very easily with a simple PowerShell function:</p>

<div class="wp_syntax"><div class="code"><pre class="powershell" style="font-family:monospace;"><span style="color: #0000FF;">function</span> Get<span style="color: pink;">-</span>AssemblyStrongName<span style="color: #000000;">&#40;</span><span style="color: #800080;">$assemblyPath</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #000000;">&#91;</span>System.Reflection.AssemblyName<span style="color: #000000;">&#93;</span>::<span style="color: #800000;">GetAssembly</span>Name<span style="color: #000000;">&#40;</span><span style="color: #800080;">$assemblyPath</span><span style="color: #000000;">&#41;</span>.FullName
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Simply give the assembly&#8217;s full path and you&#8217;ll get the strong name in return.</p>
<p>Personnaly, I have that in my <em>$profile</em> file and have an alias <em>gan</em> for it.</p>
]]></content>
		<link rel="replies" type="text/html" href="http://www.pvle.be/2010/04/getting-an-assemblys-strong-name-with-powershell/#comments" thr:count="0" />
		<link rel="replies" type="application/atom+xml" href="http://www.pvle.be/2010/04/getting-an-assemblys-strong-name-with-powershell/feed/atom/" thr:count="0" />
		<thr:total>0</thr:total>
	</entry>
		<entry>
		<author>
			<name>Philippe</name>
						<uri>http://www.pvle.be</uri>
					</author>
		<title type="html"><![CDATA[Why I Love Extension Methods]]></title>
		<link rel="alternate" type="text/html" href="http://www.pvle.be/2009/11/why-i-love-extension-methods/" />
		<id>http://www.pvle.be/2009/11/why-i-love-extension-methods/</id>
		<updated>2009-11-30T07:52:08Z</updated>
		<published>2009-11-30T07:52:08Z</published>
		<category scheme="http://www.pvle.be" term="Uncategorized" /><category scheme="http://www.pvle.be" term=".NET" /><category scheme="http://www.pvle.be" term="Extension Methods" /><category scheme="http://www.pvle.be" term="Html Agility Pack" />		<summary type="html"><![CDATA[The other day, I was using for the first time the Html Agility Pack library.
The method I use the most is the SelectNodes to which you give an XPath and that returns an HtlmNodeCollection containing the resulting HtmlNodes or null if no node where found.
I don’t know if this is a design decision, but returning [...]]]></summary>
		<content type="html" xml:base="http://www.pvle.be/2009/11/why-i-love-extension-methods/"><![CDATA[<p>The other day, I was using for the first time the <a href="http://www.codeplex.com/htmlagilitypack">Html Agility Pack</a> library.</p>
<p>The method I use the most is the <em>SelectNodes</em> to which you give an <a href="http://en.wikipedia.org/wiki/XPath">XPath</a> and that returns an <em>HtlmNodeCollection</em> containing the resulting <em>HtmlNode</em>s or <em>null</em> if no node where found.</p>
<p>I don’t know if this is a design decision, but returning null when there is no match is not very nice. If you use the expression as is in a foreach statement, it will throw a <a href="http://msdn.microsoft.com/en-us/library/system.nullreferenceexception.aspx">NullReferenceException</a> if no match.</p>
<p>A simple solution is to use the coalescing operator next to the function’s call, in order to give the <em>foreach</em> an empty <em>Enumerable</em> to avoid the exception.</p>
<pre class="code">htmlNode.SelectNodes(xpath) ?? <span style="color: #2b91af">Enumerable</span>.Empty&lt;<span style="color: #2b91af">HtmlNode</span>&gt;()</pre>
<p><a href="http://11011.net/software/vspaste"></a>This is working well, but it’s a bit ugly to repeat that in every <em>foreach</em> statement.</p>
<p>This is where <a href="http://msdn.microsoft.com/en-us/library/bb383977.aspx">Extension Methods</a> are so enjoyable. Let’s just add a new method to our <em>HtmlNode</em> friend that returns an empty enumerable when <em>SelectNodes</em> return <em>null</em>.</p>
<pre class="code"><span style="color: blue">internal static class </span><span style="color: #2b91af">HtmlAgilityPackExtension
</span>{
<span style="color: blue">    internal static </span><span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: #2b91af">HtmlNode</span>&gt; SelectNodesOrEmpty(<span style="color: blue">this </span><span style="color: #2b91af">HtmlNode </span>htmlNode, <span style="color: #2b91af">String </span>xpath)
    {
        <span style="color: blue">return </span>htmlNode.SelectNodes(xpath) ?? <span style="color: #2b91af">Enumerable</span>.Empty&lt;<span style="color: #2b91af">HtmlNode</span>&gt;();
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>There we go. From now on, I can simply <em>foreach</em> over a <em>SelectNodesOrEmpty</em> result of any <em>HtmlNode,</em> with no fear of any exception.</p>
]]></content>
		<link rel="replies" type="text/html" href="http://www.pvle.be/2009/11/why-i-love-extension-methods/#comments" thr:count="1" />
		<link rel="replies" type="application/atom+xml" href="http://www.pvle.be/2009/11/why-i-love-extension-methods/feed/atom/" thr:count="1" />
		<thr:total>1</thr:total>
	</entry>
		<entry>
		<author>
			<name>Philippe</name>
						<uri>http://www.pvle.be</uri>
					</author>
		<title type="html"><![CDATA[Value Types Initialisation]]></title>
		<link rel="alternate" type="text/html" href="http://www.pvle.be/2009/11/value-types-initialisation/" />
		<id>http://www.pvle.be/2009/11/value-types-initialisation/</id>
		<updated>2009-11-20T19:49:17Z</updated>
		<published>2009-11-20T19:49:17Z</published>
		<category scheme="http://www.pvle.be" term="Uncategorized" />		<summary type="html"><![CDATA[Value Types are a bit special. I won’t go down to the basics, but the differ from Reference Types by holding directly a value instead of a reference.
There are two interesting cases that I’m going to elaborate on. They pretty much make sense, but a little explanation cannot hurt.
Prelude
Here is a very simple struct that [...]]]></summary>
		<content type="html" xml:base="http://www.pvle.be/2009/11/value-types-initialisation/"><![CDATA[<p>Value Types are a bit special. I won’t go down to the basics, but the differ from Reference Types by holding directly a value instead of a reference.</p>
<p>There are two interesting cases that I’m going to elaborate on. They pretty much make sense, but a little explanation cannot hurt.</p>
<h3>Prelude</h3>
<p>Here is a very simple <em>struct</em> that I will use to demonstrate my point:</p>
<pre class="code"><span style="color: blue">struct </span><span style="color: #2b91af">DaysAndHours
</span>{
    <span style="color: blue">public int </span>Days { <span style="color: blue">get</span>; <span style="color: blue">private set</span>; }
    <span style="color: blue">public int </span>Hours { <span style="color: blue">get</span>; <span style="color: blue">private set</span>; }

    <span style="color: blue">public override string </span>ToString()
    {
        <span style="color: blue">return </span><span style="color: #2b91af">String</span>.Format(<span style="color: #a31515">&quot;{0} day(s) and {1} hour(s)&quot;</span>, Days, Hours);
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Notes:</p>
<ul>
<li>Structs cannot have custom default (parameter less) constructors. They however can have other custom constructors. This means that the default constructor can always be called, and that all the fields from the <em>struct</em> will be initialised at there default value; </li>
<li>Overriding the <em>ToString</em> method is a good idea. It’s always a good idea, even more with a <em>struct</em> as this will prevent boxing of the variable when <em>ToString</em> called. </li>
</ul>
<h3>The “unassigned” Value Type</h3>
<p>Now, let’s say that I declare a variable of this type, and never assign it. The normal rules of the compiler will apply:</p>
<ul>
<li>When you declare a variable somewhere, without initialising it, the compiler will issue a warning saying that the variable is declared but never used. </li>
<li>If you try to access one of it’s field, it will issue an error saying that the variable cannot be used because it is unassigned. </li>
</ul>
<p>However, if you run the debugger, you can see the variable’s content. If it was a Reference Type, it would be null, but in this case, you can see all that the content is there, with all the fields being at their default value:</p>
<p><img title="StructsInitialisation01" style="border-top-width: 0px; display: block; border-left-width: 0px; float: none; border-bottom-width: 0px; margin-left: auto; margin-right: auto; border-right-width: 0px" height="75" alt="StructsInitialisation01" src="http://www.pvle.be/wp-content/2009/11/StructsInitialisation01.png" width="311" border="0" /></p>
<p>The trick is that, when declaring the variable <em>dh</em>, the instance is allocated on the stack. However, the C# compiler don’t let you do that and wants to make sure you called the <em>new</em> keyword for that value type.</p>
<h3>The Backing Field&#160; Issue</h3>
<p>In my <em>struct</em>, I lazily used automatically implemented properties that were introduced in C# 3. This leads to a compiler error when using a custom constructor like this one:</p>
<pre class="code"><span style="color: blue">public </span>DaysAndHours(<span style="color: blue">int </span>days, <span style="color: blue">int </span>hours)
{
    Days = days;
    Hours = hours;
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>The compiler will report the following error:</p>
<blockquote>
<p><em>Backing field for automatically implemented property &#8216;DaysAndHours.Days&#8217; must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer.</em></p>
</blockquote>
<p>This makes a lot of sense, as the backing fields for these properties have not been initialized. However, we cannot access the backing field, so we cannot initialize the field. Hopefully, the default parameter less constructor will do that, so calling it is sufficient to make sure the backing fields are initialized:</p>
<pre class="code"><span style="color: blue">public </span>DaysAndHours(<span style="color: blue">int </span>days, <span style="color: blue">int </span>hours) : <span style="color: blue">this</span>()
{
    Days = days;
    Hours = hours;
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<h3>Conclusion</h3>
<p>Always remember that you cannot prevent a <em>struct</em> to be constructed using the default constructor, that has the same visibility as the <em>struct</em> itself. If you are using automatic properties, you have to explicitly call the default constructor in order to initialise the backing fields as you can’t access them directly.</p>
]]></content>
		<link rel="replies" type="text/html" href="http://www.pvle.be/2009/11/value-types-initialisation/#comments" thr:count="0" />
		<link rel="replies" type="application/atom+xml" href="http://www.pvle.be/2009/11/value-types-initialisation/feed/atom/" thr:count="0" />
		<thr:total>0</thr:total>
	</entry>
	</feed>
