<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Alkampfer&#039;s Place&#187; Languages</title>
	<atom:link href="http://www.codewrecks.com/blog/index.php/category/programming/languages/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.codewrecks.com/blog</link>
	<description>Wrecks of code floating in the sea of Internet By Ricci Gian Maria</description>
	<lastBuildDate>Wed, 08 Feb 2012 17:49:48 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2</generator>
		<item>
		<title>Extend BindingList with filter functionality</title>
		<link>http://www.codewrecks.com/blog/index.php/2008/11/22/extend-bindinglist-with-filter-functionality/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2008/11/22/extend-bindinglist-with-filter-functionality/#comments</comments>
		<pubDate>Sat, 22 Nov 2008 11:14:16 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Languages]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[Software Architecture]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/index.php/2008/11/22/extend-bindinglist-with-filter-functionality/</guid>
		<description><![CDATA[If you still work with windows forms and cannot move all of your projects to WPF, you probably gets annoyed by the limitation of the standard BindingList&#60;T&#62; included in the framework. In an old post I showed how can you create a specialized BindingList&#60;T&#62; to support generic Find() thanks to reflection, but this is not [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2008%2F11%2F22%2Fextend-bindinglist-with-filter-functionality%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2008%2F11%2F22%2Fextend-bindinglist-with-filter-functionality%2F&amp;source=alkampfer&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>If you still work with windows forms and cannot move all of your projects to WPF, you probably gets annoyed by the limitation of the standard BindingList&lt;T&gt; included in the framework. In an <a href="http://www.codewrecks.com/blog/index.php/2007/10/12/bindinglistfind-and-notimplementedexception/">old post</a> I showed how can you create a specialized BindingList&lt;T&gt; to support generic Find() thanks to reflection, but this is not enough.</p>
<p>Another annoying limitation is that BindingList does not support IBindingListView. For those that does not knows this interface, it is the one used by the windows forms binding engine to support filtering and advanced sorting. I think that filtering is a real basic functionality needed by the binding engine, and in fact WPF support for filtering, sorting and grouping, make these operations really a breeze. But BindingList does not offers such a functionality.</p>
<p>My question is: <em>is it possible to inherits from BindingList&lt;T&gt; adding generic filtering support as for the DataView component</em>?. The answer is yes, here is a simple implementation.</p>
<p>
<div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E7:de608857-b994-4adb-b41b-595614a13852" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:White;;overflow: auto;">
<div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/

--><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">string</span><span style="color: #000000;"> Filter
{
    </span><span style="color: #0000FF;">get</span><span style="color: #000000;">
    {
        </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> filterClause;
    }
    </span><span style="color: #0000FF;">set</span><span style="color: #000000;">
    {
        </span><span style="color: #0000FF;">if</span><span style="color: #000000;"> (filterClause </span><span style="color: #000000;">==</span><span style="color: #000000;"> value) </span><span style="color: #0000FF;">return</span><span style="color: #000000;">;
        filterClause </span><span style="color: #000000;">=</span><span style="color: #000000;"> value;
        DoFilter();
    }
}</span></div>
</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>
<p>This is really simple, I implement the FIlter property with a simple check, if the filterClause changes, I call the DoFilter function.</p>
<p><div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E7:b8433304-b00b-4678-beb8-ee43366860bd" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:White;;overflow: auto;">
<div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/

--><span style="color: #0000FF;">private</span><span style="color: #000000;"> Func</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">T, Boolean</span><span style="color: #000000;">&gt;</span><span style="color: #000000;"> filterPredicate;

</span><span style="color: #0000FF;">private</span><span style="color: #000000;"> List</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">T</span><span style="color: #000000;">&gt;</span><span style="color: #000000;"> original </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #0000FF;">new</span><span style="color: #000000;"> List</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">T</span><span style="color: #000000;">&gt;</span><span style="color: #000000;">();

</span><span style="color: #0000FF;">private</span><span style="color: #000000;"> </span><span style="color: #0000FF;">void</span><span style="color: #000000;"> DoFilter()
{
    </span><span style="color: #0000FF;">if</span><span style="color: #000000;"> (String.IsNullOrEmpty(filterClause))
    {
        Items.Clear();
        original.ForEach(e </span><span style="color: #000000;">=&gt;</span><span style="color: #000000;"> Items.Add(e));
    }
    </span><span style="color: #0000FF;">else</span><span style="color: #000000;">
    {
        original.Clear();
        original.AddRange(Items);
        Items.Clear();
        filterPredicate </span><span style="color: #000000;">=</span><span style="color: #000000;"> DynamicLinq.ParseToFunction</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">T, Boolean</span><span style="color: #000000;">&gt;</span><span style="color: #000000;">(filterClause);
        </span><span style="color: #0000FF;">foreach</span><span style="color: #000000;"> (T element </span><span style="color: #0000FF;">in</span><span style="color: #000000;"> original.Where(filterPredicate))
           Items.Add(element);
    }
}</span></div>
</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>
<p>The implementation is based on this standard trick, if a filter is applied I copy all the elements in a temp list, then clear the base.Items list and add again only the elements that satisfies the filter. The big work is done in DynamicLinq.ParseToFunction that takes a string and dynamically compiles a function with that criteria. Here is a simple <a title="test" href="http://www.codewrecks.com/blog/index.php/2007/09/03/test/">test</a> showing this class in action.</p>
<div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E7:3d8e51f2-bca9-4bd9-914c-4ded1c5abc29" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:White;;overflow: auto;">
<div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/

--><span style="color: #000000;">[Test]
</span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">void</span><span style="color: #000000;"> TestLogicAnd()
{
    Func</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">Customer, Boolean</span><span style="color: #000000;">&gt;</span><span style="color: #000000;"> f </span><span style="color: #000000;">=</span><span style="color: #000000;"> DynamicLinq.ParseToFunction</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">Customer, Boolean</span><span style="color: #000000;">&gt;</span><span style="color: #000000;">(</span><span style="color: #800000;">&quot;</span><span style="color: #800000;">Name == 'Gian Maria' &amp;&amp; Age &gt; 5</span><span style="color: #800000;">&quot;</span><span style="color: #000000;">);
    Assert.That(f(aCustomer), Is.True);
}</span></div>
</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>
</p>
<p>Actually I use three main component, a tokenizer that takes a string and separates into token, then I pass the tokenized expression (is a List&lt;String&gt;) to another component that convert the infix form in postfix form (<a target="_blank" href="http://en.wikipedia.org/wiki/Reverse_Polish_notation">reverse Polish</a>), finally I create an expression from the reverse Polish form, creates a LambdaExpression on it and finally call compile() to make dynamic generation happens. The result is a dynamic generator of <a title="LINQ" href="http://www.codewrecks.com/blog/index.php/category/net-framework/linq/">LINQ</a> expression from a string. It still misses a lot, you cannot express condition on nested properties and parameter support is still experimental, but the basic is there.</p>
<p>The code is still under development, if you are curios you can check out the repository at <a target="_blank" title="http://dotnetmarcheproject.googlecode.com/svn/trunk" href="http://dotnetmarcheproject.googlecode.com/svn/trunk">http://dotnetmarcheproject.googlecode.com/svn/trunk</a> the code is still in rough form, but if you like it you can give it a shot. The class is the BindingListExt&lt;T&gt;</p>
<p>Alk.</p>
<p>Tags: <a target="_blank" href="http://technorati.com/tag/BindingList" rel="tag">BindingList</a> <a target="_blank" href="http://technorati.com/tag/IBindingView" rel="tag">IBindingView</a> <a target="_blank" href="http://technorati.com/tag/Dynamic Expression Parser" rel="tag">Dynamic Expression Parser</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2008/11/22/extend-bindinglist-with-filter-functionality/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Story of a stupid bug, difference between struct and class</title>
		<link>http://www.codewrecks.com/blog/index.php/2008/06/24/stupid-bug-difference-between-struct-and-class/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2008/06/24/stupid-bug-difference-between-struct-and-class/#comments</comments>
		<pubDate>Tue, 24 Jun 2008 14:18:53 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Languages]]></category>

		<guid isPermaLink="false">http://www.codewrecks.com/blog/index.php/2008/06/24/stupid-bug-difference-between-struct-and-class/</guid>
		<description><![CDATA[I&#8217;ve incurred in a very stupid bug this afternoon, I run test on a new version of a component and I see that a lot of exceptions are raised about violating unique constraint of a simple strongly typed dataset I use to log information in database. After a brief look at the code I found [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2008%2F06%2F24%2Fstupid-bug-difference-between-struct-and-class%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2008%2F06%2F24%2Fstupid-bug-difference-between-struct-and-class%2F&amp;source=alkampfer&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>I&#8217;ve incurred in a very stupid bug this afternoon, I run <a title="test" href="http://www.codewrecks.com/blog/index.php/2007/09/03/test/">test</a> on a new version of a component and I see that a lot of exceptions are raised about violating unique constraint of a simple strongly typed dataset I use to log information in database.</p>
<p>After a brief look at the code I found that I create new guid with the instruction <em>new Guid(), </em>I was really surprised because I really know that new guid should be created with Guid.NewGuid(). This is indeed caused by the fact that Guid() is a structure and not a class. The following <a title="test" href="http://www.codewrecks.com/blog/index.php/2007/09/03/test/">test</a> demonstrate this fact</p>
<p>
<div class="wlWriterSmartContent" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E7:2de7038b-713a-4845-acc4-88cf097caddb" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre style="background-color:White;;overflow: auto;">
<div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/

--><span style="color: #000000;">[Test]
</span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">void</span><span style="color: #000000;"> CreateGuid()
{
    Assert.That(</span><span style="color: #0000FF;">new</span><span style="color: #000000;"> Guid(), Is.EqualTo(Guid.Empty));
    Assert.That(Guid.NewGuid(), Is.Not.EqualTo(Guid.Empty));
}</span></div>
</pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>
<p>This test will succeeds because Guid is a value type, and he always has a default constructor that can be called to create empty instance of the structure. If you look into the documentation of Guid you can in fact verify that default constructor is not even listed between the valid ones.</p>
<p>This is one of the most annoying difference from reference and value type: value type always have a default constructor and you cannot prevent the user to use it.</p>
<p>alk.</p>
<p>Tags: <a target="_blank" href="http://technorati.com/tag/.net value type" rel="tag">.net value type</a> </p>
<div class="wlWriterSmartContent" id="scid:C16BAC14-9A3D-4c50-9394-FBFEF7A93539:3012ff21-e746-4c32-8686-daea295c9a45" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px"><!--dotnetkickit--></div>]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2008/06/24/stupid-bug-difference-between-struct-and-class/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A generic IComparer that works with reflection</title>
		<link>http://www.codewrecks.com/blog/index.php/2007/07/02/a-generic-icomparer-that-works-with-reflection/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2007/07/02/a-generic-icomparer-that-works-with-reflection/#comments</comments>
		<pubDate>Mon, 02 Jul 2007 13:41:53 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Languages]]></category>
		<category><![CDATA[Nhibernate]]></category>

		<guid isPermaLink="false">http://www.nablasoft.com/Alkampfer/?p=79</guid>
		<description><![CDATA[Today I was speaking with a colleague about creating a generic IComparer&#60;T&#62; that is able to compare two object based on a property discovered through reflection. Such object will be very useful to sort or find object inside collection of objects when you work with a domain model. In a domain we usually have a [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2007%2F07%2F02%2Fa-generic-icomparer-that-works-with-reflection%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2007%2F07%2F02%2Fa-generic-icomparer-that-works-with-reflection%2F&amp;source=alkampfer&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>Today I was speaking with a colleague about creating a generic IComparer&lt;T&gt; that is able to compare two object based on a property discovered through reflection. Such object will be very useful to sort or find object inside collection of objects when you work with a <a title="domain model" href="http://www.codewrecks.com/blog/index.php/tag/domain-model/">domain model</a>. In a domain we usually have a lot of objects such as customer, order, and so on, and it happens to have an homogeneous collection of objects in memory that needs to be sorted. Implementing an IComparer object for each combination of property and type is really boring so it useful to create a class capable to compare object based on reflection. A first implementation of the IComparer&lt;T&gt;::Compare() method could be the following
</p>
<p><span style="font-family:Consolas"><span style="color:blue">public</span>Ã‚Â <span style="color:blue">int</span>Ã‚Â Compare(TÃ‚Â x,Ã‚Â TÃ‚Â y)Ã‚Â {<span style="color:black">Ã‚Â Ã‚Â Ã‚Â Ã‚Â <br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â PropertyInfoÃ‚Â propertyInfoÃ‚Â =Ã‚Â </span><span style="color:blue">typeof</span><span style="color:black">(T).GetProperty(SortColumn);<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â </span><span style="color:#2b91af">IComparable</span><span style="color:black">Ã‚Â obj1Ã‚Â =Ã‚Â (</span><span style="color:#2b91af">IComparable</span><span style="color:black">)propertyInfo.GetValue(x,Ã‚Â </span><span style="color:blue">null</span><span style="color:black">);<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â </span><span style="color:#2b91af">IComparable</span><span style="color:black">Ã‚Â obj2Ã‚Â =Ã‚Â (</span><span style="color:#2b91af">IComparable</span><span style="color:black">)propertyInfo.GetValue(y,Ã‚Â </span><span style="color:blue">null</span><span style="color:black">);<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">return</span><span style="color:black">Ã‚Â (obj1.CompareTo(obj2));<br/>}<br />
</span></span></p>
<p>This implementation works as expected, but it has bad <a title="performance" href="http://www.codewrecks.com/blog/index.php/tag/performance/">performance</a>, this because it use reflection to find propertyInfo at each calls of the Compare() method. Since we are dealing with homogeneous collections I know in advance that the collection contains objects of a same type, so a better strategy is to cache the MethodInfo related to the GetterPart of the property into the constructor of the comparer object.
</p>
<p><span style="font-family:Consolas"><span style="color:black">Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">public</span><span style="color:black">Ã‚Â </span><span style="color:blue">class</span><span style="color:black">Ã‚Â </span><span style="color:#2b91af">GenericIComparer</span><span style="color:black">&lt;T&gt;Ã‚Â :Ã‚Â </span><span style="color:#2b91af">IComparer</span><span style="color:black">&lt;T&gt;Ã‚Â {<br/>Ã‚Â <br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">private</span><span style="color:black">Ã‚Â </span><span style="color:blue">readonly</span><span style="color:black">Ã‚Â </span><span style="color:#2b91af">MethodBase</span><span style="color:black">Ã‚Â methodInfo;<br/>Ã‚Â <br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">internal</span><span style="color:black">Ã‚Â GenericIComparer(</span><span style="color:#2b91af">MethodBase</span><span style="color:black">Ã‚Â methodInfo,Ã‚Â </span><span style="color:#2b91af">Boolean</span><span style="color:black">Ã‚Â reversed)Ã‚Â {<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">this</span><span style="color:black">.methodInfoÃ‚Â =Ã‚Â methodInfo;<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â mReversedÃ‚Â =Ã‚Â reversed;<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â }<br/>Ã‚Â <br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">public</span><span style="color:black">Ã‚Â GenericIComparer(</span><span style="color:#2b91af">String</span><span style="color:black">Ã‚Â propname)<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â :Ã‚Â </span><span style="color:blue">this</span><span style="color:black">(propname,Ã‚Â </span><span style="color:blue">false</span><span style="color:black">)Ã‚Â {<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â }<br/>Ã‚Â <br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">public</span><span style="color:black">Ã‚Â GenericIComparer(</span><span style="color:#2b91af">String</span><span style="color:black">Ã‚Â propname,Ã‚Â </span><span style="color:blue">bool</span><span style="color:black">Ã‚Â mReversed)Ã‚Â :<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">this</span><span style="color:black">(</span><span style="color:blue">typeof</span><span style="color:black">(T).GetProperty(propname).GetGetMethod(),Ã‚Â mReversed)Ã‚Â {Ã‚Â }<br/>Ã‚Â <br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">public</span><span style="color:black">Ã‚Â </span><span style="color:blue">bool</span><span style="color:black">Ã‚Â ReversedÃ‚Â {<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">get</span><span style="color:black">Ã‚Â {Ã‚Â </span><span style="color:blue">return</span><span style="color:black">Ã‚Â mReversed;Ã‚Â }<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">set</span><span style="color:black">Ã‚Â {Ã‚Â mReversedÃ‚Â =Ã‚Â </span><span style="color:blue">value</span><span style="color:black">;Ã‚Â }<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â }<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">private</span><span style="color:black">Ã‚Â </span><span style="color:#2b91af">Boolean</span><span style="color:black">Ã‚Â mReversedÃ‚Â =Ã‚Â </span><span style="color:blue">false</span><span style="color:black">;<br/>Ã‚Â <br/></span><span style="color:blue">Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â #region</span><span style="color:black">Ã‚Â IComparer&lt;T&gt;Ã‚Â Members<br/>Ã‚Â <br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">public</span><span style="color:black">Ã‚Â </span><span style="color:blue">int</span><span style="color:black">Ã‚Â Compare(TÃ‚Â x,Ã‚Â TÃ‚Â y)Ã‚Â {<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â </span><span style="color:#2b91af">IComparable</span><span style="color:black">Ã‚Â obj1Ã‚Â =Ã‚Â (</span><span style="color:#2b91af">IComparable</span><span style="color:black">)methodInfo.Invoke(x,Ã‚Â </span><span style="color:blue">null</span><span style="color:black">);<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â </span><span style="color:#2b91af">IComparable</span><span style="color:black">Ã‚Â obj2Ã‚Â =Ã‚Â (</span><span style="color:#2b91af">IComparable</span><span style="color:black">)methodInfo.Invoke(y,Ã‚Â </span><span style="color:blue">null</span><span style="color:black">);<br/>Ã‚Â <br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â </span><span style="color:#2b91af">Int32</span><span style="color:black">Ã‚Â resultÃ‚Â =Ã‚Â (obj1.CompareTo(obj2));<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">return</span><span style="color:black">Ã‚Â mReversedÃ‚Â ?Ã‚Â -resultÃ‚Â :Ã‚Â result;<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â }<br/>Ã‚Â <br/></span><span style="color:blue">Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â #endregion</span><span style="color:black"><br/>Ã‚Â Ã‚Â Ã‚Â }<br />
</span></span></p>
<p>This version support a property called Reversed that is used to compare in reverse order. As you can see this class grab the methodInfo related to the getter part of the property in the constructor, to reduce calls to GetProperty() function. As you can see this class has an internal constructor that accepts a MethodBase passed from the caller, this is necessary to go a step further into the optimization, a factory class that optimize the creation of GenericIComparer objects.
</p>
<p><span style="font-family:Consolas"><span style="color:black">Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">public</span><span style="color:black">Ã‚Â </span><span style="color:blue">static</span><span style="color:black">Ã‚Â </span><span style="color:blue">class</span><span style="color:black">Ã‚Â </span><span style="color:#2b91af">GenericComparerFactory</span><span style="color:black">Ã‚Â {<br/>Ã‚Â <br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">private</span><span style="color:black">Ã‚Â </span><span style="color:blue">readonly</span><span style="color:black">Ã‚Â </span><span style="color:blue">static</span><span style="color:black">Ã‚Â </span><span style="color:#2b91af">Dictionary</span><span style="color:black">&lt;</span><span style="color:#2b91af">Type</span><span style="color:black">,Ã‚Â </span><span style="color:#2b91af">Dictionary</span><span style="color:black">&lt;</span><span style="color:#2b91af">String</span><span style="color:black">,Ã‚Â </span><span style="color:#2b91af">RuntimeMethodHandle</span><span style="color:black">&gt;&gt;Ã‚Â comparersÃ‚Â =<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">new</span><span style="color:black">Ã‚Â </span><span style="color:#2b91af">Dictionary</span><span style="color:black">&lt;</span><span style="color:#2b91af">Type</span><span style="color:black">,Ã‚Â </span><span style="color:#2b91af">Dictionary</span><span style="color:black">&lt;</span><span style="color:blue">string</span><span style="color:black">,Ã‚Â </span><span style="color:#2b91af">RuntimeMethodHandle</span><span style="color:black">&gt;&gt;();<br/>Ã‚Â <br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">public</span><span style="color:black">Ã‚Â </span><span style="color:blue">static</span><span style="color:black">Ã‚Â </span><span style="color:#2b91af">GenericIComparer</span><span style="color:black">&lt;T&gt;Ã‚Â GetComparer&lt;T&gt;(</span><span style="color:blue">string</span><span style="color:black">Ã‚Â propertyName,Ã‚Â </span><span style="color:blue">bool</span><span style="color:black">Ã‚Â reversed)Ã‚Â {<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â </span><span style="color:green">//CheckÃ‚Â ifÃ‚Â theÃ‚Â typeÃ‚Â arrayÃ‚Â forÃ‚Â thisÃ‚Â comparerÃ‚Â wasÃ‚Â created.</span><span style="color:black"><br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">if</span><span style="color:black">Ã‚Â (!comparers.ContainsKey(</span><span style="color:blue">typeof</span><span style="color:black">(T)))<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â comparers.Add(</span><span style="color:blue">typeof</span><span style="color:black">(T),Ã‚Â </span><span style="color:blue">new</span><span style="color:black">Ã‚Â </span><span style="color:#2b91af">Dictionary</span><span style="color:black">&lt;</span><span style="color:blue">string</span><span style="color:black">,Ã‚Â </span><span style="color:#2b91af">RuntimeMethodHandle</span><span style="color:black">&gt;());<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">if</span><span style="color:black">Ã‚Â (!comparers[</span><span style="color:blue">typeof</span><span style="color:black">(T)].ContainsKey(propertyName))<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â comparers[</span><span style="color:blue">typeof</span><span style="color:black">(T)].Add(<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â propertyName,Ã‚Â <br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">typeof</span><span style="color:black">(T).GetProperty(propertyName).GetGetMethod().MethodHandle);<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">return</span><span style="color:black">Ã‚Â (</span><span style="color:#2b91af">GenericIComparer</span><span style="color:black">&lt;T&gt;)Ã‚Â </span><span style="color:blue">new</span><span style="color:black">Ã‚Â </span><span style="color:#2b91af">GenericIComparer</span><span style="color:black">&lt;T&gt;(Ã‚Â <br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â </span><span style="color:#2b91af">MethodInfo</span><span style="color:black">.GetMethodFromHandle(comparers[</span><span style="color:blue">typeof</span><span style="color:black">(T)][propertyName]),Ã‚Â reversed);<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â }<br/>Ã‚Â <br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">public</span><span style="color:black">Ã‚Â </span><span style="color:blue">static</span><span style="color:black">Ã‚Â </span><span style="color:#2b91af">GenericIComparer</span><span style="color:black">&lt;T&gt;Ã‚Â GetComparer&lt;T&gt;(</span><span style="color:blue">string</span><span style="color:black">Ã‚Â propertyName)Ã‚Â {<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">return</span><span style="color:black">Ã‚Â GetComparer&lt;T&gt;(propertyName);<br/>Ã‚Â <br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â }<br/>Ã‚Â Ã‚Â Ã‚Â }<br />
</span></span></p>
<p>This class hold a dictionary of propertyName, RuntimeMethodHandle objects for each type. The RuntimeMethodHandle is a further optimization to save memory used to store MethodInfo objects. A MethodInfo object is a big object to store into memory, so it has a readonly property called <em>MethodHandle</em> that will return a IntPtr that uniquely identify that method info. The GenericComparerFactory can reduce the use of the memory, storing into the dictionary a IntPtr object, and recreating the MethodInfo object with the GetMethodFromHandle() function of the MethodInfo object only when it is necessary. With these optimization the GenericIComparer has a small memory footprint and maximum <a title="performance" href="http://www.codewrecks.com/blog/index.php/tag/performance/">performance</a>.
</p>
<p>Alk.
</p>
<p> Ã‚Â </p>]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2007/07/02/a-generic-icomparer-that-works-with-reflection/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>C# anonymous delegates and template pattern</title>
		<link>http://www.codewrecks.com/blog/index.php/2007/06/05/c-anonymous-delegates-and-template-pattern-2/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2007/06/05/c-anonymous-delegates-and-template-pattern-2/#comments</comments>
		<pubDate>Tue, 05 Jun 2007 08:31:07 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Languages]]></category>

		<guid isPermaLink="false">http://www.nablasoft.com/Alkampfer/?p=64</guid>
		<description><![CDATA[Yesterday I blogged on a slightly modified version of Ayende code posted here, this makes me reflect on template pattern of the GOF. Template pattern is one of the most useful pattern, and is used when you have a common block of code that is to be repeated in may part with a little customization. [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2007%2F06%2F05%2Fc-anonymous-delegates-and-template-pattern-2%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2007%2F06%2F05%2Fc-anonymous-delegates-and-template-pattern-2%2F&amp;source=alkampfer&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>Yesterday I blogged on a slightly modified version of Ayende code posted <a target="_blank" href="http://ayende.com/Blog/archive/2007/05/27/Reflections-on-the-Naked-CLR.aspx">here</a>, this makes me reflect on template pattern of the GOF. Template pattern is one of the most useful pattern, and is used when you have a common block of code that is to be repeated in may part with a little customization. In the GOF the intent of the pattern is
</p>
<p><em>Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template method lets subclasses redefine certain steps of an algorithm without changing the algorithm&#8217;s structure.<br />
</em></p>
<p>The original description of the pattern explicitly states that the implementation is made by a template class (usually abstract) and then a series of subclasses, each for a different variation of the algorithm that is to be implemented. C# anonymous delegates are a great way to implement a template pattern even with a static class, without the need to use subclasses or inheritance. The post from Ayende is a great example of this. In his code Ayende creates a base method that accepts a delegate with all the common infrastructure to execute ad Ado<a title=".NET" href="http://www.codewrecks.com/blog/index.php/tag/net/">.NET</a> DbCommand. In the base static function he creates connection, starts a transaction and creates a command that will be attached to an open connection, then he calls the delegates passed as an argument. With anonymous delegate the caller is able to specify a block of code that logically will be substituted into the inner part of the Template static method. This kind of implementation can also be done in C++ with function pointer, but is definitively not so readable as counterpart in C#.
</p>
<p>Alk.</p>]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2007/06/05/c-anonymous-delegates-and-template-pattern-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The old plain C language</title>
		<link>http://www.codewrecks.com/blog/index.php/2007/05/28/the-old-plain-c-language/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2007/05/28/the-old-plain-c-language/#comments</comments>
		<pubDate>Mon, 28 May 2007 05:24:24 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Languages]]></category>

		<guid isPermaLink="false">http://www.nablasoft.com/Alkampfer/?p=51</guid>
		<description><![CDATA[A friend of mine is taking a basic course in computer programming, and actually he is studying the basic of C language. Yesterday he told me that he must do a very simple exercise that will print on screen a triangle like thisXXXXXXXXXXXXXXXXXXXXXXXXXXXAnd so on. He asked me if I could review his solution before [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2007%2F05%2F28%2Fthe-old-plain-c-language%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2007%2F05%2F28%2Fthe-old-plain-c-language%2F&amp;source=alkampfer&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>A friend of mine is taking a basic course in computer <a title="programming" href="http://www.codewrecks.com/blog/index.php/category/programming/">programming</a>, and actually he is studying the basic of C language. Yesterday he told me that he must do a very simple exercise that will print on screen a triangle like this<br/><span style="font-family:Consolas"><span style="font-size:9pt">XXXXXXXXXX<br/>XXXXXXXXX<br/>XXXXXXXX</span><span style="font-size:10pt"><br/></span></span>And so on. He asked me if I could review his solution before he give his program to the teacher, because he is moving from the old house to a new house and actually he do not have access to a computer to try his solution. This morning I decided to refresh my knowledge of C solving this simple exercise, I must admit that I love C/C++Ã¢â‚¬Â¦.I cannot explain but they are really fascinating <a title="languages" href="http://www.codewrecks.com/blog/index.php/category/programming/languages/">languages</a> (I love assembly language too)
</p>
<p><span style="font-family:Consolas"><span style="color:blue">#include</span><span style="color:black">Ã‚Â </span><span style="color:#a31515">&#8220;stdio.h&#8221;</span><span style="color:black"><br/></span><span style="color:blue">#include</span><span style="color:black">Ã‚Â </span><span style="color:#a31515">&#8220;memory.h&#8221;</span><span style="color:black"><br/>Ã‚Â <br/></span><span style="color:blue">#define</span><span style="color:black">Ã‚Â NUM_OF_CHARSÃ‚Â 10<br/>Ã‚Â <br/></span><span style="color:blue">int</span><span style="color:black">Ã‚Â main()Ã‚Â {<br/>Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">char</span><span style="color:black">Ã‚Â str[NUM_OF_CHARSÃ‚Â +Ã‚Â 1];<br/>Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">int</span><span style="color:black">Ã‚Â I;<br/>Ã‚Â Ã‚Â Ã‚Â memset(str,Ã‚Â </span><span style="color:#a31515">&#8216;X&#8217;</span><span style="color:black">,Ã‚Â NUM_OF_CHARS);<br/>Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">for</span><span style="color:black">Ã‚Â (IÃ‚Â =Ã‚Â NUM_OF_CHARS;Ã‚Â IÃ‚Â &gt;Ã‚Â 0;Ã‚Â &#8211;I)Ã‚Â {<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â str[I]Ã‚Â =Ã‚Â </span><span style="color:#a31515">&#8216; &#8242;</span><span style="color:black">;Ã‚Â <br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â printf(</span><span style="color:#a31515">&#8220;%sn&#8221;</span><span style="color:black">,Ã‚Â str);<br/>Ã‚Â Ã‚Â Ã‚Â }Ã‚Â <br/>}<br />
</span></span></p>
<p>The ability to manage memory of a string is one of the feature that I missed most when I program in C#.
</p>
<p>Alk.</p>]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2007/05/28/the-old-plain-c-language/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Difference between C# and VB, simple add</title>
		<link>http://www.codewrecks.com/blog/index.php/2007/05/26/difference-between-c-and-vb-simple-add/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2007/05/26/difference-between-c-and-vb-simple-add/#comments</comments>
		<pubDate>Sat, 26 May 2007 07:21:44 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Languages]]></category>

		<guid isPermaLink="false">http://www.nablasoft.com/Alkampfer/?p=50</guid>
		<description><![CDATA[Sometimes differences between C# and VB could be subtle, for example consider these very simple two snippets of code, what they will print? Ã‚Â Ã‚Â Ã‚Â SubÃ‚Â Main()Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Console.WriteLine(&#8220;ResultÃ‚Â isÃ‚Â &#8220;Ã‚Â +Ã‚Â Sum(Integer.MaxValue,Ã‚Â 1))Ã‚Â Ã‚Â Ã‚Â EndÃ‚Â SubÃ‚Â Ã‚Â Ã‚Â Ã‚Â PublicÃ‚Â FunctionÃ‚Â Sum(ByValÃ‚Â aÃ‚Â AsÃ‚Â Integer,Ã‚Â ByValÃ‚Â bÃ‚Â AsÃ‚Â Integer)Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â ReturnÃ‚Â aÃ‚Â +Ã‚Â bÃ‚Â Ã‚Â Ã‚Â EndÃ‚Â FunctionÃ‚Â Ã‚Â Ã‚Â staticÃ‚Â voidÃ‚Â Main(string[]Ã‚Â args)Ã‚Â {Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Console.WriteLine(&#8220;ResultÃ‚Â isÃ‚Â &#8220;Ã‚Â +Ã‚Â Sum(Int32.MaxValue,Ã‚Â 1));Ã‚Â Ã‚Â Ã‚Â }Ã‚Â Ã‚Â Ã‚Â Ã‚Â publicÃ‚Â staticÃ‚Â Int32Ã‚Â Sum(Int32Ã‚Â a,Ã‚Â Int32Ã‚Â b)Ã‚Â {Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â returnÃ‚Â aÃ‚Â +Ã‚Â b;Ã‚Â Ã‚Â Ã‚Â } The first snipped written in VB throws a System.OverflowException, because the result of the operation cannot be stored into an integer value. The behavior of C# can be more surprising because [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2007%2F05%2F26%2Fdifference-between-c-and-vb-simple-add%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2007%2F05%2F26%2Fdifference-between-c-and-vb-simple-add%2F&amp;source=alkampfer&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>Sometimes differences between C# and VB could be subtle, for example consider these very simple two snippets of code, what they will print?
</p>
<p style="background: white"><span style="font-family:Consolas"><span style="color:blue">Ã‚Â Ã‚Â Ã‚Â Sub</span><span style="color:black">Ã‚Â Main()<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Console.WriteLine(</span><span style="color:#a31515">&#8220;ResultÃ‚Â isÃ‚Â &#8220;</span><span style="color:black">Ã‚Â +Ã‚Â Sum(</span><span style="color:blue">Integer</span><span style="color:black">.MaxValue,Ã‚Â 1))<br/>Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">End</span><span style="color:black">Ã‚Â </span><span style="color:blue">Sub</span><span style="color:black"><br/>Ã‚Â <br/>Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">Public</span><span style="color:black">Ã‚Â </span><span style="color:blue">Function</span><span style="color:black">Ã‚Â Sum(</span><span style="color:blue">ByVal</span><span style="color:black">Ã‚Â aÃ‚Â </span><span style="color:blue">As</span><span style="color:black">Ã‚Â </span><span style="color:blue">Integer</span><span style="color:black">,Ã‚Â </span><span style="color:blue">ByVal</span><span style="color:black">Ã‚Â bÃ‚Â </span><span style="color:blue">As</span><span style="color:black">Ã‚Â </span><span style="color:blue">Integer</span><span style="color:black">)<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">Return</span><span style="color:black">Ã‚Â aÃ‚Â +Ã‚Â b<br/>Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">End</span><span style="color:black">Ã‚Â </span><span style="color:blue">Function<br/><br/></span><span style="color:black">Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">static</span><span style="color:black">Ã‚Â </span><span style="color:blue">void</span><span style="color:black">Ã‚Â Main(</span><span style="color:blue">string</span><span style="color:black">[]Ã‚Â args)Ã‚Â {<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â </span><span style="color:#2b91af">Console</span><span style="color:black">.WriteLine(</span><span style="color:#a31515">&#8220;ResultÃ‚Â isÃ‚Â &#8220;</span><span style="color:black">Ã‚Â +Ã‚Â Sum(</span><span style="color:#2b91af">Int32</span><span style="color:black">.MaxValue,Ã‚Â 1));<br/>Ã‚Â Ã‚Â Ã‚Â }<br/>Ã‚Â <br/>Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">public</span><span style="color:black">Ã‚Â </span><span style="color:blue">static</span><span style="color:black">Ã‚Â </span><span style="color:#2b91af">Int32</span><span style="color:black">Ã‚Â Sum(</span><span style="color:#2b91af">Int32</span><span style="color:black">Ã‚Â a,Ã‚Â </span><span style="color:#2b91af">Int32</span><span style="color:black">Ã‚Â b)Ã‚Â {<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">return</span><span style="color:black">Ã‚Â aÃ‚Â +Ã‚Â b;<br/>Ã‚Â Ã‚Â Ã‚Â }<br/><br />
			</span></span></p>
<p>The first snipped written in VB throws a System.OverflowException, because the result of the operation cannot be stored into an integer value. The behavior of C# can be more surprising because it print <strong><em>Result is -2147483648</em></strong> showing a result that is clearly wrong. This example shows that VB and C# have very different semantic even for basic operation. But what is the reason for such a different behavior? If we look at MSIL code we can see that VB compiler produces this code
</p>
<p><span style="font-family:Consolas; font-size:10pt">Ã‚Â Ã‚Â Ã‚Â Ã‚Â L_0002:Ã‚Â ldarg.1Ã‚Â <br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â L_0003:Ã‚Â add.ovfÃ‚Â <br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â L_0004:Ã‚Â boxÃ‚Â <a target="_blank" href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:2.0.0.0:b77a5c561934e089/System.Int32" title="int32"><span style="color:#006018">int32</span></a>Ã‚Â <br/>Ã‚Â <br/></span>As you can see the add operation gets translated with opcode <strong><em>add.ofv</em></strong>, where ofv means overflow. This particular operation throws an exception if the result of the operation will result in a overflow. C# generates this snippet.
</p>
<p><span style="font-family:Consolas; font-size:10pt">Ã‚Â Ã‚Â Ã‚Â Ã‚Â L_0002:Ã‚Â ldarg.1Ã‚Â <br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â L_0003:Ã‚Â addÃ‚Â <br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â L_0004:Ã‚Â stloc.0<br/><br/></span>Generated MSIL is different because C# compiler use the <em><strong>add</strong><br />
		</em>opcode that will not check for an overflow. The question is: why such different behavior? VB<a title=".NET" href="http://www.codewrecks.com/blog/index.php/tag/net/">.NET</a> descends from VB6 where all arithmetic operations are checked, so this semantic is maintained even if for .NET version, C# descends from C++ where aritmetic operation does not check for an overflow. The primary reason is efficiency, let&#8217;s look at real IA32 code generated by the JIT compiler through disassembly window. This is the assembly generated for the add.ofv opcode (VB).
</p>
<p><span style="font-family:Consolas; font-size:10pt">Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â DimÃ‚Â resultÃ‚Â AsÃ‚Â IntegerÃ‚Â =Ã‚Â aÃ‚Â +Ã‚Â b<br/>0000002eÃ‚Â Ã‚Â movÃ‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â eax,ebxÃ‚Â <br/>00000030Ã‚Â Ã‚Â addÃ‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â eax,dwordÃ‚Â ptrÃ‚Â [ebp-40h]Ã‚Â <br/>00000033Ã‚Â Ã‚Â jnoÃ‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â 0000003AÃ‚Â <br/>00000035Ã‚Â Ã‚Â callÃ‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â 79747E72Ã‚Â <br/>0000003aÃ‚Â Ã‚Â movÃ‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â dwordÃ‚Â ptrÃ‚Â [ebp-44h],eax<br/></span><br/>After the add operation there is a <strong><em>jno</em></strong> opcode that means &#8220;<strong><em>Jump if not overflow</em></strong>&#8220;, if the operation will result in a overflow, the instruction does not jump and instruction at offset 35 calls a system routine that will throw the exception. The cost of checking overflow is a <a title="branch" href="http://www.codewrecks.com/blog/index.php/tag/branch/">branch</a> instruction after every arithmetic operation, for this reason C# compiler does not insert overflow check instruction for arithmetic operation. If you don&#8217;t like this, you can force C# compiler to insert overflow checking instruction with <em>checked </em>keyword
</p>
<p><span style="font-family:Consolas"><span style="color:blue">checked</span><span style="color:black">Ã‚Â {<br/>Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">return</span><span style="color:black">Ã‚Â aÃ‚Â +Ã‚Â b;<br/>}Ã‚Â<br />
</span></span></p>
<p>With the checked keyword we can choose to do checked operation only for specific parts of the code. VB is less flexible, because has a compiler operation that will disable overflow check for all the assembly, not showing the granularity of C#.
</p>
<p>Alk. </p>]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2007/05/26/difference-between-c-and-vb-simple-add/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Casting in Visual Basic .NET</title>
		<link>http://www.codewrecks.com/blog/index.php/2007/05/15/casting-in-visual-basic-net/</link>
		<comments>http://www.codewrecks.com/blog/index.php/2007/05/15/casting-in-visual-basic-net/#comments</comments>
		<pubDate>Tue, 15 May 2007 13:50:32 +0000</pubDate>
		<dc:creator>alkampfer</dc:creator>
				<category><![CDATA[Languages]]></category>

		<guid isPermaLink="false">http://www.nablasoft.com/Alkampfer/?p=36</guid>
		<description><![CDATA[In all type safe languages there is the concept of &#8220;casting&#8221;, an operation used to specify to the compiler that a variable of a certain Type has to be considered of different Type. Visual Basic has three operators to do a cast: DirectCast, CType and TryCast, each one behaving in a different way from the [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a target="_blank" href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2007%2F05%2F15%2Fcasting-in-visual-basic-net%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.codewrecks.com%2Fblog%2Findex.php%2F2007%2F05%2F15%2Fcasting-in-visual-basic-net%2F&amp;source=alkampfer&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>In all type safe <a title="languages" href="http://www.codewrecks.com/blog/index.php/category/programming/languages/">languages</a> there is the concept of &#8220;casting&#8221;, an operation used to specify to the compiler that a variable of a certain Type has to be considered of different Type. Visual Basic has three operators to do a cast: <em>DirectCast, CType </em>and <em>TryCast</em>, each one behaving in a different way from the other. To understand the subtle differences from these three operators lets present a simple example.
</p>
<p style="background: white"><span style="font-family:Consolas"><span style="color:blue">Ã‚Â Ã‚Â Ã‚Â Private</span><span style="color:black">Ã‚Â </span><span style="color:blue">Sub</span><span style="color:black">Ã‚Â DirectCastExample(</span><span style="color:blue">ByVal</span><span style="color:black">Ã‚Â objÃ‚Â </span><span style="color:blue">As</span><span style="color:black">Ã‚Â </span><span style="color:blue">Object</span><span style="color:black">)<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Console.WriteLine(</span><span style="color:#a31515">&#8220;stringÃ‚Â lenght={0}&#8221;</span><span style="color:black">,Ã‚Â </span><span style="color:blue">DirectCast</span><span style="color:black">(obj,Ã‚Â </span><span style="color:blue">String</span><span style="color:black">).Length)<br/>Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">End</span><span style="color:black">Ã‚Â </span><span style="color:blue">Sub</span><span style="color:black"><br/>Ã‚Â <br/>Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">Private</span><span style="color:black">Ã‚Â </span><span style="color:blue">Sub</span><span style="color:black">Ã‚Â CTypeExample(</span><span style="color:blue">ByVal</span><span style="color:black">Ã‚Â objÃ‚Â </span><span style="color:blue">As</span><span style="color:black">Ã‚Â </span><span style="color:blue">Object</span><span style="color:black">)<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Console.WriteLine(</span><span style="color:#a31515">&#8220;stringÃ‚Â lenght={0}&#8221;</span><span style="color:black">,Ã‚Â </span><span style="color:blue">CType</span><span style="color:black">(obj,Ã‚Â </span><span style="color:blue">String</span><span style="color:black">).Length)<br/>Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">End</span><span style="color:black">Ã‚Â </span><span style="color:blue">Sub</span><span style="color:black"><br/>Ã‚Â <br/>Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">Private</span><span style="color:black">Ã‚Â </span><span style="color:blue">Sub</span><span style="color:black">Ã‚Â trycastExample(</span><span style="color:blue">ByVal</span><span style="color:black">Ã‚Â objÃ‚Â </span><span style="color:blue">As</span><span style="color:black">Ã‚Â </span><span style="color:blue">Object</span><span style="color:black">)<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Console.WriteLine(</span><span style="color:#a31515">&#8220;stringÃ‚Â lenght={0}&#8221;</span><span style="color:black">,Ã‚Â </span><span style="color:blue">TryCast</span><span style="color:black">(obj,Ã‚Â </span><span style="color:blue">String</span><span style="color:black">).Length)<br/>Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">End</span><span style="color:black">Ã‚Â </span><span style="color:blue">Sub</span><span style="color:black"><br/><br/>Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">Private</span><span style="color:black">Ã‚Â </span><span style="color:blue">Sub</span><span style="color:black">Ã‚Â <a title="Test" href="http://www.codewrecks.com/blog/index.php/2007/09/03/test/">Test</a>()<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â DirectCastExample(30)<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â CTypeExample(30)<br/>Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â Ã‚Â trycastExample(30)<br/>Ã‚Â Ã‚Â Ã‚Â </span><span style="color:blue">End</span><span style="color:black">Ã‚Â </span><span style="color:blue">Sub</span><span style="color:black"><br/><br />
			</span></span></p>
<p>The three instruction of the <a title="Test" href="http://www.codewrecks.com/blog/index.php/2007/09/03/test/">Test</a>() function give really three different results, the first throws an InvalidCastException, the second writes &#8220;string length=2&#8243; and the third throws a NullReferenceException. To understand what is happening we could look at generated MSIL . DirectCast operator is translated with this code
</p>
<p>L_0007: castclass <a target="_blank" href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:2.0.0.0:b77a5c561934e089/System.String" title="string">string</a><br/>L_000c: callvirt instance <a target="_blank" href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:2.0.0.0:b77a5c561934e089/System.Int32" title="int32">int32</a> [<a target="_blank" href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:2.0.0.0:b77a5c561934e089" title="mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">mscorlib</a>]<a target="_blank" href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:2.0.0.0:b77a5c561934e089/System.String" title="[mscorlib]System.String">System.String</a>::<a target="_blank" href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:2.0.0.0:b77a5c561934e089/System.String/get_Length():Int32" title="get_Length">get_Length</a>()
</p>
<p>DirectCast is translated to castclass opcode, that simply pushes on the stack the object reference to the cast instance. If at run time the instance passed to the function is not a String class an InvalidCastException is thrown. DirectCast can convert if the object is of the exact type, if inherits from the type specified, or if the object implements the interface when the destination type is an interface.
</p>
<p>TryCast operator behaves a little different, this is the MSIL generated
</p>
<p>L_0007: isinst <a target="_blank" href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:2.0.0.0:b77a5c561934e089/System.String" title="string">string</a><br/>L_000c: callvirt instance <a target="_blank" href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:2.0.0.0:b77a5c561934e089/System.Int32" title="int32">int32</a> [<a target="_blank" href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:2.0.0.0:b77a5c561934e089" title="mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">mscorlib</a>]<a target="_blank" href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:2.0.0.0:b77a5c561934e089/System.String" title="[mscorlib]System.String">System.String</a>::<a target="_blank" href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:2.0.0.0:b77a5c561934e089/System.String/get_Length():Int32" title="get_Length">get_Length</a>()
</p>
<p>TryCast  use the isinst opcode, that is analogous to castclass, but if the cast is not successful instead of throwing an exception a null value is push on the stack. The third type of cast, CType is not really a cast operator, but instead a conversion operator, even if in a lot of documentation CType is considered to be a cast operator, to understand the difference here is generated MSIL.
</p>
<p>L_0007: call <a target="_blank" href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:2.0.0.0:b77a5c561934e089/System.String" title="string">string</a> [<a target="_blank" href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://Microsoft.VisualBasic:8.0.0.0:b03f5f7f11d50a3a" title="Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">Microsoft.VisualBasic</a>]<a target="_blank" href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://Microsoft.VisualBasic:8.0.0.0:b03f5f7f11d50a3a/Microsoft.VisualBasic.CompilerServices.Conversions" title="[Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.Conversions">Microsoft.VisualBasic.CompilerServices.Conversions</a>::<a target="_blank" href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://Microsoft.VisualBasic:8.0.0.0:b03f5f7f11d50a3a/Microsoft.VisualBasic.CompilerServices.Conversions/ToString(Object):String" title="ToString">ToString</a>(<a target="_blank" href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:2.0.0.0:b77a5c561934e089/System.Object" title="object">object</a>)<br/>L_000c: callvirt instance <a target="_blank" href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:2.0.0.0:b77a5c561934e089/System.Int32" title="int32">int32</a> [<a target="_blank" href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:2.0.0.0:b77a5c561934e089" title="mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">mscorlib</a>]<a target="_blank" href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:2.0.0.0:b77a5c561934e089/System.String" title="[mscorlib]System.String">System.String</a>::<a target="_blank" href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:2.0.0.0:b77a5c561934e089/System.String/get_Length():Int32" title="get_Length">get_Length</a>()
</p>
<p>As you can see CType operator calls internally the function ToString() of class Microsoft.VisualBasic.CompilerServices.Conversions, this means that CType does not make a cast, but it makes conversions. The example in fact reveals that when we pass the integer value 30 to the function, this value gets converted to the string &#8220;30&#8243; and the code does not throw errors. The annoying issue is that you use CType to convert a variable to a custom type class it defaults to use castclass opcode, since the Microsoft.VisualBasic.CompilerServices.Conversion has methods to convert only to .NET basic types.
</p>
<p>Alk.
</p>
<p>
Ã‚Â </p>
<p>
Ã‚Â </p>]]></content:encoded>
			<wfw:commentRss>http://www.codewrecks.com/blog/index.php/2007/05/15/casting-in-visual-basic-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

