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

<channel>
	<title>Noldorin</title>
	<atom:link href="http://alexreg.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://alexreg.wordpress.com</link>
	<description>Musings on my countless projects, software, science, and various other curiosities</description>
	<lastBuildDate>Mon, 12 Sep 2011 20:18:57 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='alexreg.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://0.gravatar.com/blavatar/e532e100492dae9c67d5060ef85a5ac2?s=96&#038;d=http%3A%2F%2Fs2.wp.com%2Fi%2Fbuttonw-com.png</url>
		<title>Noldorin</title>
		<link>http://alexreg.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://alexreg.wordpress.com/osd.xml" title="Noldorin" />
	<atom:link rel='hub' href='http://alexreg.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Blog Relocated</title>
		<link>http://alexreg.wordpress.com/2009/08/21/blog-relocated/</link>
		<comments>http://alexreg.wordpress.com/2009/08/21/blog-relocated/#comments</comments>
		<pubDate>Fri, 21 Aug 2009 09:46:11 +0000</pubDate>
		<dc:creator>Noldorin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[blog]]></category>
		<category><![CDATA[blog moved]]></category>
		<category><![CDATA[blog relocated]]></category>
		<category><![CDATA[personal website]]></category>
		<category><![CDATA[website]]></category>
		<category><![CDATA[wordpress]]></category>

		<guid isPermaLink="false">http://alexreg.wordpress.com/?p=240</guid>
		<description><![CDATA[This blog has been relocated to my personal website, where all existing posts are mirrored. You can view it at http://blog.noldorin.com. &#160; (Please update your feeds list, as this WordPress.com blog will no longer be in use for any purposes.) Posted in Uncategorized Tagged: blog, blog moved, blog relocated, personal website, website, wordpress<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=alexreg.wordpress.com&amp;blog=3367172&amp;post=240&amp;subd=alexreg&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h2>This blog has been relocated to my personal website, where all existing posts are mirrored. You can view it at <a href="http://noldorin.com/blog/"><strong>http://blog.noldorin.com</strong></a>.</h2>
<p>&nbsp;</p>
<p><strong>(Please update your feeds list, as this WordPress.com blog will no longer be in use for any purposes.)</strong></p>
<br />Posted in Uncategorized Tagged: blog, blog moved, blog relocated, personal website, website, wordpress <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/alexreg.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/alexreg.wordpress.com/240/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/alexreg.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/alexreg.wordpress.com/240/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/alexreg.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/alexreg.wordpress.com/240/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/alexreg.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/alexreg.wordpress.com/240/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/alexreg.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/alexreg.wordpress.com/240/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/alexreg.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/alexreg.wordpress.com/240/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/alexreg.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/alexreg.wordpress.com/240/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=alexreg.wordpress.com&amp;blog=3367172&amp;post=240&amp;subd=alexreg&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://alexreg.wordpress.com/2009/08/21/blog-relocated/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eed60bdfc964ec62cc48aa6020a03d7b?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=PG" medium="image">
			<media:title type="html">Noldorin</media:title>
		</media:content>
	</item>
		<item>
		<title>Searching for Exceptions in .NET</title>
		<link>http://alexreg.wordpress.com/2009/06/22/searching-for-exceptions-in-net/</link>
		<comments>http://alexreg.wordpress.com/2009/06/22/searching-for-exceptions-in-net/#comments</comments>
		<pubDate>Mon, 22 Jun 2009 15:33:18 +0000</pubDate>
		<dc:creator>Noldorin</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[cil]]></category>
		<category><![CDATA[clr]]></category>
		<category><![CDATA[control flow]]></category>
		<category><![CDATA[errors]]></category>
		<category><![CDATA[exceptions]]></category>
		<category><![CDATA[extension methods]]></category>
		<category><![CDATA[instructions]]></category>
		<category><![CDATA[libraries]]></category>
		<category><![CDATA[methods]]></category>
		<category><![CDATA[msil]]></category>
		<category><![CDATA[reflection]]></category>
		<category><![CDATA[stack]]></category>
		<category><![CDATA[stackoverflow]]></category>
		<category><![CDATA[third-party libraries]]></category>
		<category><![CDATA[try-catch]]></category>
		<category><![CDATA[variables]]></category>
		<category><![CDATA[xml comments]]></category>
		<category><![CDATA[xml documentation]]></category>

		<guid isPermaLink="false">http://alexreg.wordpress.com/?p=228</guid>
		<description><![CDATA[I recently came across a rather interesting question on StackOverflow that posed the problem of discovering all the exceptions that a given method might throw under every circumstance. Of course, in the great majority of situations, XML  documentation for the BCL (and ideally any third-party libraries too) should provide information about any exception that might [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=alexreg.wordpress.com&amp;blog=3367172&amp;post=228&amp;subd=alexreg&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I recently came across <a href="http://stackoverflow.com/questions/986180/how-can-i-determine-which-exceptions-can-be-thrown-by-a-given-method/997931#997931">a rather interesting question on StackOverflow</a> that posed the problem of discovering all the exceptions that a given method might throw under every circumstance.</p>
<p>Of course, in the great majority of situations, XML  documentation for the BCL (and ideally any third-party libraries too) should provide information about any exception that might be thrown and any potential reason for it. Indeed, thisthis is generally all one needs to write largely error-safe code. However, not <em>every</em> exception is documented in any case, and for production-quality applications, it is often desirable to insure that there is no realistic chance of an unhandled exception ocurring. For this reason, it is sometimes desirable to do a rigorous check for all exceptions. Clearly, an application-level unhandled (fatal) exception handler would do the job to some extent, and although this is always a good fallback feature to have, it is the least elegant solution to coping with exceptions.</p>
<p>After some consideration, it became quite apparent that the task reduces to the <a href="http://en.wikipedia.org/wiki/Halting_problem">halting problem</a>. However, with a few simplifications, the problem does become relatively solvable. Most importantly, complex logic that determines whether an exception will be thrown must be ignored, and one must simply assume that any throw statement within a given method could possibly cause an exception under certain conditions.</p>
<p>Here is the complete code for the algorithm I wrote. The <em>GetAllExceptions</em> method is an extension method that returns a read-only collection of exceptions, which makes it very straightforward and efficient to use.</p>
<p>Notably, the code detects all of</p>
<ul>
<li>instantiated exceptions,</li>
<li>exceptions return from method/property calls,</li>
<li>exceptions stored in fields (though if the method return type or field type is non-specific, i.e. a parent class of the actual exception type thrown), this is used instead.</li>
</ul>
<p>Exceptions are only counted when the appropiate <em>throw</em> instruction is encountered at some level. Also, the stack and local variables are handled correctly, as far as I can tell, so this method should work soundly in pretty much all cases. (It has been tested with some a few quite complex methods within the BCL, as well as simpler user-defined ones.)</p>
<pre class="csharp" style="font-family:monospace;color:#006;border:1px solid #d0d0d0;background-color:#f0f0f0;margin-bottom:1em;max-height:40em;overflow:scroll;"><span style="color:#0600FF;">using</span> <span style="color:#008080;">System</span><span style="color:#008000;">;</span>
<span style="color:#0600FF;">using</span> <span style="color:#008080;">System.Collections.Generic</span><span style="color:#008000;">;</span>
<span style="color:#0600FF;">using</span> <span style="color:#008080;">System.Collections.ObjectModel</span><span style="color:#008000;">;</span>
<span style="color:#0600FF;">using</span> <span style="color:#008080;">System.Linq</span><span style="color:#008000;">;</span>
<span style="color:#0600FF;">using</span> <span style="color:#008080;">System.Reflection</span><span style="color:#008000;">;</span>
<span style="color:#0600FF;">using</span> <span style="color:#008080;">System.Reflection.Emit</span><span style="color:#008000;">;</span>
<span style="color:#0600FF;">using</span> <span style="color:#008080;">System.Text</span><span style="color:#008000;">;</span>
<span style="color:#0600FF;">using</span> <span style="color:#008080;">ClrTest.Reflection</span><span style="color:#008000;">;</span>

<span style="color:#0600FF;">public</span> <span style="color:#0600FF;">static</span> <span style="color:#FF0000;">class</span> ExceptionAnalyser
<span style="color:#000000;">{</span>
    <span style="color:#0600FF;">public</span> <span style="color:#0600FF;">static</span> ReadOnlyCollection<span style="color:#008000;">&lt;</span>Type<span style="color:#008000;">&gt;</span> GetAllExceptions<span style="color:#000000;">(</span><span style="color:#0600FF;">this</span> MethodBase method<span style="color:#000000;">)</span>
    <span style="color:#000000;">{</span>
        var exceptionTypes <span style="color:#008000;">=</span> <a style="color:#000060;" href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color:#008000;">new</span></a> HashSet<span style="color:#008000;">&lt;</span>Type<span style="color:#008000;">&gt;</span><span style="color:#000000;">(</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
        var visitedMethods <span style="color:#008000;">=</span> <a style="color:#000060;" href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color:#008000;">new</span></a> HashSet<span style="color:#008000;">&lt;</span>MethodBase<span style="color:#008000;">&gt;</span><span style="color:#000000;">(</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
        var localVars <span style="color:#008000;">=</span> <a style="color:#000060;" href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color:#008000;">new</span></a> Type<span style="color:#000000;">[</span><span style="color:#FF0000;">ushort</span>.<span style="color:#0000FF;">MaxValue</span><span style="color:#000000;">]</span><span style="color:#008000;">;</span>
        var stack <span style="color:#008000;">=</span> <a style="color:#000060;" href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color:#008000;">new</span></a> Stack<span style="color:#008000;">&lt;</span>Type<span style="color:#008000;">&gt;</span><span style="color:#000000;">(</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
        GetAllExceptions<span style="color:#000000;">(</span>method, exceptionTypes, visitedMethods, localVars, stack, 0<span style="color:#000000;">)</span><span style="color:#008000;">;</span>

        <span style="color:#0600FF;">return</span> exceptionTypes.<span style="color:#0000FF;">ToList</span><span style="color:#000000;">(</span><span style="color:#000000;">)</span>.<span style="color:#0000FF;">AsReadOnly</span><span style="color:#000000;">(</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
    <span style="color:#000000;">}</span>

    <span style="color:#0600FF;">public</span> <span style="color:#0600FF;">static</span> <span style="color:#0600FF;">void</span> GetAllExceptions<span style="color:#000000;">(</span>MethodBase method, HashSet<span style="color:#008000;">&lt;</span>Type<span style="color:#008000;">&gt;</span> exceptionTypes,
        HashSet<span style="color:#008000;">&lt;</span>MethodBase<span style="color:#008000;">&gt;</span> visitedMethods, Type<span style="color:#000000;">[</span><span style="color:#000000;">]</span> localVars, Stack<span style="color:#008000;">&lt;</span>Type<span style="color:#008000;">&gt;</span> stack, <span style="color:#FF0000;">int</span> depth<span style="color:#000000;">)</span>
    <span style="color:#000000;">{</span>
        var ilReader <span style="color:#008000;">=</span> <a style="color:#000060;" href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color:#008000;">new</span></a> ILReader<span style="color:#000000;">(</span>method<span style="color:#000000;">)</span><span style="color:#008000;">;</span>
        var allInstructions <span style="color:#008000;">=</span> ilReader.<span style="color:#0000FF;">ToArray</span><span style="color:#000000;">(</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>

        ILInstruction instruction<span style="color:#008000;">;</span>
        <span style="color:#0600FF;">for</span> <span style="color:#000000;">(</span><span style="color:#FF0000;">int</span> i <span style="color:#008000;">=</span> <span style="color:#FF0000;">0</span><span style="color:#008000;">;</span> i <span style="color:#008000;">&lt;</span> allInstructions.<span style="color:#0000FF;">Length</span><span style="color:#008000;">;</span> i<span style="color:#008000;">++</span><span style="color:#000000;">)</span>
        <span style="color:#000000;">{</span>
            instruction <span style="color:#008000;">=</span> allInstructions<span style="color:#000000;">[</span>i<span style="color:#000000;">]</span><span style="color:#008000;">;</span>

            <span style="color:#0600FF;">if</span> <span style="color:#000000;">(</span>instruction <a style="color:#000060;" href="http://www.google.com/search?q=is+msdn.microsoft.com"><span style="color:#008000;">is</span></a> InlineMethodInstruction<span style="color:#000000;">)</span>
            <span style="color:#000000;">{</span>
                var methodInstruction <span style="color:#008000;">=</span> <span style="color:#000000;">(</span>InlineMethodInstruction<span style="color:#000000;">)</span>instruction<span style="color:#008000;">;</span>

                <span style="color:#0600FF;">if</span> <span style="color:#000000;">(</span><span style="color:#008000;">!</span>visitedMethods.<span style="color:#0000FF;">Contains</span><span style="color:#000000;">(</span>methodInstruction.<span style="color:#0000FF;">Method</span><span style="color:#000000;">)</span><span style="color:#000000;">)</span>
                <span style="color:#000000;">{</span>
                    visitedMethods.<span style="color:#0000FF;">Add</span><span style="color:#000000;">(</span>methodInstruction.<span style="color:#0000FF;">Method</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
                    GetAllExceptions<span style="color:#000000;">(</span>methodInstruction.<span style="color:#0000FF;">Method</span>, exceptionTypes, visitedMethods,
                        localVars, stack, depth <span style="color:#008000;">+</span> 1<span style="color:#000000;">)</span><span style="color:#008000;">;</span>
                <span style="color:#000000;">}</span>

                var curMethod <span style="color:#008000;">=</span> methodInstruction.<span style="color:#0000FF;">Method</span><span style="color:#008000;">;</span>
                <span style="color:#0600FF;">if</span> <span style="color:#000000;">(</span>curMethod <a style="color:#000060;" href="http://www.google.com/search?q=is+msdn.microsoft.com"><span style="color:#008000;">is</span></a> ConstructorInfo<span style="color:#000000;">)</span>
                    stack.<span style="color:#0000FF;">Push</span><span style="color:#000000;">(</span><span style="color:#000000;">(</span><span style="color:#000000;">(</span>ConstructorInfo<span style="color:#000000;">)</span>curMethod<span style="color:#000000;">)</span>.<span style="color:#0000FF;">DeclaringType</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
                <span style="color:#0600FF;">else</span> <span style="color:#0600FF;">if</span> <span style="color:#000000;">(</span>method <a style="color:#000060;" href="http://www.google.com/search?q=is+msdn.microsoft.com"><span style="color:#008000;">is</span></a> MethodInfo<span style="color:#000000;">)</span>
                    stack.<span style="color:#0000FF;">Push</span><span style="color:#000000;">(</span><span style="color:#000000;">(</span><span style="color:#000000;">(</span>MethodInfo<span style="color:#000000;">)</span>curMethod<span style="color:#000000;">)</span>.<span style="color:#0000FF;">ReturnParameter</span>.<span style="color:#0000FF;">ParameterType</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
            <span style="color:#000000;">}</span>
            <span style="color:#0600FF;">else</span> <span style="color:#0600FF;">if</span> <span style="color:#000000;">(</span>instruction <a style="color:#000060;" href="http://www.google.com/search?q=is+msdn.microsoft.com"><span style="color:#008000;">is</span></a> InlineFieldInstruction<span style="color:#000000;">)</span>
            <span style="color:#000000;">{</span>
                var fieldInstruction <span style="color:#008000;">=</span> <span style="color:#000000;">(</span>InlineFieldInstruction<span style="color:#000000;">)</span>instruction<span style="color:#008000;">;</span>
                stack.<span style="color:#0000FF;">Push</span><span style="color:#000000;">(</span>fieldInstruction.<span style="color:#0000FF;">Field</span>.<span style="color:#0000FF;">FieldType</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
            <span style="color:#000000;">}</span>
            <span style="color:#0600FF;">else</span> <span style="color:#0600FF;">if</span> <span style="color:#000000;">(</span>instruction <a style="color:#000060;" href="http://www.google.com/search?q=is+msdn.microsoft.com"><span style="color:#008000;">is</span></a> ShortInlineBrTargetInstruction<span style="color:#000000;">)</span>
            <span style="color:#000000;">{</span>
            <span style="color:#000000;">}</span>
            <span style="color:#0600FF;">else</span> <span style="color:#0600FF;">if</span> <span style="color:#000000;">(</span>instruction <a style="color:#000060;" href="http://www.google.com/search?q=is+msdn.microsoft.com"><span style="color:#008000;">is</span></a> InlineBrTargetInstruction<span style="color:#000000;">)</span>
            <span style="color:#000000;">{</span>
            <span style="color:#000000;">}</span>
            <span style="color:#0600FF;">else</span>
            <span style="color:#000000;">{</span>
                <span style="color:#0600FF;">switch</span> <span style="color:#000000;">(</span>instruction.<span style="color:#0000FF;">OpCode</span>.<span style="color:#0000FF;">Value</span><span style="color:#000000;">)</span>
                <span style="color:#000000;">{</span>
                    <span style="color:#008080;font-style:italic;">// ld*</span>
                    <span style="color:#0600FF;">case</span> 0x06<span style="color:#008000;">:</span>
                        stack.<span style="color:#0000FF;">Push</span><span style="color:#000000;">(</span>localVars<span style="color:#000000;">[</span>0<span style="color:#000000;">]</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
                        break<span style="color:#008000;">;</span>
                    <span style="color:#0600FF;">case</span> 0x07<span style="color:#008000;">:</span>
                        stack.<span style="color:#0000FF;">Push</span><span style="color:#000000;">(</span>localVars<span style="color:#000000;">[</span>1<span style="color:#000000;">]</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
                        break<span style="color:#008000;">;</span>
                    <span style="color:#0600FF;">case</span> 0x08<span style="color:#008000;">:</span>
                        stack.<span style="color:#0000FF;">Push</span><span style="color:#000000;">(</span>localVars<span style="color:#000000;">[</span>2<span style="color:#000000;">]</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
                        break<span style="color:#008000;">;</span>
                    <span style="color:#0600FF;">case</span> 0x09<span style="color:#008000;">:</span>
                        stack.<span style="color:#0000FF;">Push</span><span style="color:#000000;">(</span>localVars<span style="color:#000000;">[</span>3<span style="color:#000000;">]</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
                        break<span style="color:#008000;">;</span>
                    <span style="color:#0600FF;">case</span> 0x11<span style="color:#008000;">:</span>
                        <span style="color:#000000;">{</span>
                            var index <span style="color:#008000;">=</span> <span style="color:#000000;">(</span><span style="color:#FF0000;">ushort</span><span style="color:#000000;">)</span>allInstructions<span style="color:#000000;">[</span>i <span style="color:#008000;">+</span> 1<span style="color:#000000;">]</span>.<span style="color:#0000FF;">OpCode</span>.<span style="color:#0000FF;">Value</span><span style="color:#008000;">;</span>
                            stack.<span style="color:#0000FF;">Push</span><span style="color:#000000;">(</span>localVars<span style="color:#000000;">[</span>index<span style="color:#000000;">]</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
                            break<span style="color:#008000;">;</span>
                        <span style="color:#000000;">}</span>
                    <span style="color:#008080;font-style:italic;">// st*</span>
                    <span style="color:#0600FF;">case</span> 0x0A<span style="color:#008000;">:</span>
                        localVars<span style="color:#000000;">[</span>0<span style="color:#000000;">]</span> <span style="color:#008000;">=</span> stack.<span style="color:#0000FF;">Pop</span><span style="color:#000000;">(</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
                        break<span style="color:#008000;">;</span>
                    <span style="color:#0600FF;">case</span> 0x0B<span style="color:#008000;">:</span>
                        localVars<span style="color:#000000;">[</span>1<span style="color:#000000;">]</span> <span style="color:#008000;">=</span> stack.<span style="color:#0000FF;">Pop</span><span style="color:#000000;">(</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
                        break<span style="color:#008000;">;</span>
                    <span style="color:#0600FF;">case</span> 0x0C<span style="color:#008000;">:</span>
                        localVars<span style="color:#000000;">[</span>2<span style="color:#000000;">]</span> <span style="color:#008000;">=</span> stack.<span style="color:#0000FF;">Pop</span><span style="color:#000000;">(</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
                        break<span style="color:#008000;">;</span>
                    <span style="color:#0600FF;">case</span> 0x0D<span style="color:#008000;">:</span>
                        localVars<span style="color:#000000;">[</span>3<span style="color:#000000;">]</span> <span style="color:#008000;">=</span> stack.<span style="color:#0000FF;">Pop</span><span style="color:#000000;">(</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
                        break<span style="color:#008000;">;</span>
                    <span style="color:#0600FF;">case</span> 0x13<span style="color:#008000;">:</span>
                        <span style="color:#000000;">{</span>
                            var index <span style="color:#008000;">=</span> <span style="color:#000000;">(</span><span style="color:#FF0000;">ushort</span><span style="color:#000000;">)</span>allInstructions<span style="color:#000000;">[</span>i <span style="color:#008000;">+</span> 1<span style="color:#000000;">]</span>.<span style="color:#0000FF;">OpCode</span>.<span style="color:#0000FF;">Value</span><span style="color:#008000;">;</span>
                            localVars<span style="color:#000000;">[</span>index<span style="color:#000000;">]</span> <span style="color:#008000;">=</span> stack.<span style="color:#0000FF;">Pop</span><span style="color:#000000;">(</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
                            break<span style="color:#008000;">;</span>
                        <span style="color:#000000;">}</span>
                    <span style="color:#008080;font-style:italic;">// throw</span>
                    <span style="color:#0600FF;">case</span> 0x7A<span style="color:#008000;">:</span>
                        <span style="color:#0600FF;">if</span> <span style="color:#000000;">(</span>stack.<span style="color:#0000FF;">Peek</span><span style="color:#000000;">(</span><span style="color:#000000;">)</span> <span style="color:#008000;">==</span> <span style="color:#0600FF;">null</span><span style="color:#000000;">)</span>
                            break<span style="color:#008000;">;</span>

                        exceptionTypes.<span style="color:#0000FF;">Add</span><span style="color:#000000;">(</span>stack.<span style="color:#0000FF;">Pop</span><span style="color:#000000;">(</span><span style="color:#000000;">)</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
                        break<span style="color:#008000;">;</span>
                    <span style="color:#0600FF;">default</span><span style="color:#008000;">:</span>
                        <span style="color:#0600FF;">switch</span> <span style="color:#000000;">(</span>instruction.<span style="color:#0000FF;">OpCode</span>.<span style="color:#0000FF;">StackBehaviourPop</span><span style="color:#000000;">)</span>
                        <span style="color:#000000;">{</span>
                            <span style="color:#0600FF;">case</span> StackBehaviour.<span style="color:#0000FF;">Pop0</span><span style="color:#008000;">:</span>
                                break<span style="color:#008000;">;</span>
                            <span style="color:#0600FF;">case</span> StackBehaviour.<span style="color:#0000FF;">Pop1</span><span style="color:#008000;">:</span>
                            <span style="color:#0600FF;">case</span> StackBehaviour.<span style="color:#0000FF;">Popi</span><span style="color:#008000;">:</span>
                            <span style="color:#0600FF;">case</span> StackBehaviour.<span style="color:#0000FF;">Popref</span><span style="color:#008000;">:</span>
                            <span style="color:#0600FF;">case</span> StackBehaviour.<span style="color:#0000FF;">Varpop</span><span style="color:#008000;">:</span>
                                stack.<span style="color:#0000FF;">Pop</span><span style="color:#000000;">(</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
                                break<span style="color:#008000;">;</span>
                            <span style="color:#0600FF;">case</span> StackBehaviour.<span style="color:#0000FF;">Pop1_pop1</span><span style="color:#008000;">:</span>
                            <span style="color:#0600FF;">case</span> StackBehaviour.<span style="color:#0000FF;">Popi_pop1</span><span style="color:#008000;">:</span>
                            <span style="color:#0600FF;">case</span> StackBehaviour.<span style="color:#0000FF;">Popi_popi</span><span style="color:#008000;">:</span>
                            <span style="color:#0600FF;">case</span> StackBehaviour.<span style="color:#0000FF;">Popi_popi8</span><span style="color:#008000;">:</span>
                            <span style="color:#0600FF;">case</span> StackBehaviour.<span style="color:#0000FF;">Popi_popr4</span><span style="color:#008000;">:</span>
                            <span style="color:#0600FF;">case</span> StackBehaviour.<span style="color:#0000FF;">Popi_popr8</span><span style="color:#008000;">:</span>
                            <span style="color:#0600FF;">case</span> StackBehaviour.<span style="color:#0000FF;">Popref_pop1</span><span style="color:#008000;">:</span>
                            <span style="color:#0600FF;">case</span> StackBehaviour.<span style="color:#0000FF;">Popref_popi</span><span style="color:#008000;">:</span>
                                stack.<span style="color:#0000FF;">Pop</span><span style="color:#000000;">(</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
                                stack.<span style="color:#0000FF;">Pop</span><span style="color:#000000;">(</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
                                break<span style="color:#008000;">;</span>
                            <span style="color:#0600FF;">case</span> StackBehaviour.<span style="color:#0000FF;">Popref_popi_pop1</span><span style="color:#008000;">:</span>
                            <span style="color:#0600FF;">case</span> StackBehaviour.<span style="color:#0000FF;">Popref_popi_popi</span><span style="color:#008000;">:</span>
                            <span style="color:#0600FF;">case</span> StackBehaviour.<span style="color:#0000FF;">Popref_popi_popi8</span><span style="color:#008000;">:</span>
                            <span style="color:#0600FF;">case</span> StackBehaviour.<span style="color:#0000FF;">Popref_popi_popr4</span><span style="color:#008000;">:</span>
                            <span style="color:#0600FF;">case</span> StackBehaviour.<span style="color:#0000FF;">Popref_popi_popr8</span><span style="color:#008000;">:</span>
                            <span style="color:#0600FF;">case</span> StackBehaviour.<span style="color:#0000FF;">Popref_popi_popref</span><span style="color:#008000;">:</span>
                                stack.<span style="color:#0000FF;">Pop</span><span style="color:#000000;">(</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
                                stack.<span style="color:#0000FF;">Pop</span><span style="color:#000000;">(</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
                                stack.<span style="color:#0000FF;">Pop</span><span style="color:#000000;">(</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
                                break<span style="color:#008000;">;</span>
                        <span style="color:#000000;">}</span>

                        <span style="color:#0600FF;">switch</span> <span style="color:#000000;">(</span>instruction.<span style="color:#0000FF;">OpCode</span>.<span style="color:#0000FF;">StackBehaviourPush</span><span style="color:#000000;">)</span>
                        <span style="color:#000000;">{</span>
                            <span style="color:#0600FF;">case</span> StackBehaviour.<span style="color:#0000FF;">Push0</span><span style="color:#008000;">:</span>
                                break<span style="color:#008000;">;</span>
                            <span style="color:#0600FF;">case</span> StackBehaviour.<span style="color:#0000FF;">Push1</span><span style="color:#008000;">:</span>
                            <span style="color:#0600FF;">case</span> StackBehaviour.<span style="color:#0000FF;">Pushi</span><span style="color:#008000;">:</span>
                            <span style="color:#0600FF;">case</span> StackBehaviour.<span style="color:#0000FF;">Pushi8</span><span style="color:#008000;">:</span>
                            <span style="color:#0600FF;">case</span> StackBehaviour.<span style="color:#0000FF;">Pushr4</span><span style="color:#008000;">:</span>
                            <span style="color:#0600FF;">case</span> StackBehaviour.<span style="color:#0000FF;">Pushr8</span><span style="color:#008000;">:</span>
                            <span style="color:#0600FF;">case</span> StackBehaviour.<span style="color:#0000FF;">Pushref</span><span style="color:#008000;">:</span>
                            <span style="color:#0600FF;">case</span> StackBehaviour.<span style="color:#0000FF;">Varpush</span><span style="color:#008000;">:</span>
                                stack.<span style="color:#0000FF;">Push</span><span style="color:#000000;">(</span><span style="color:#0600FF;">null</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
                                break<span style="color:#008000;">;</span>
                            <span style="color:#0600FF;">case</span> StackBehaviour.<span style="color:#0000FF;">Push1_push1</span><span style="color:#008000;">:</span>
                                stack.<span style="color:#0000FF;">Push</span><span style="color:#000000;">(</span><span style="color:#0600FF;">null</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
                                stack.<span style="color:#0000FF;">Push</span><span style="color:#000000;">(</span><span style="color:#0600FF;">null</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
                                break<span style="color:#008000;">;</span>
                        <span style="color:#000000;">}</span>

                        break<span style="color:#008000;">;</span>
                <span style="color:#000000;">}</span>
            <span style="color:#000000;">}</span>
        <span style="color:#000000;">}</span>
    <span style="color:#000000;">}</span>
<span style="color:#000000;">}</span></pre>
<p>To be quite honest, I&#8217;m not sure whether I&#8217;ll need to use this code myself at any point, but I&#8217;ve posted it regardless for the benefit of anyone who might require such rigorous exception checking. It was definitely an interesting challenge, at the least.</p>
<p>Any further comments or suggestions would be welcome, as always.</p>
<br />Posted in Programming, Software Tagged: .net, c#, cil, clr, control flow, errors, exceptions, extension methods, instructions, libraries, methods, msil, reflection, stack, stackoverflow, third-party libraries, try-catch, variables, xml comments, xml documentation <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/alexreg.wordpress.com/228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/alexreg.wordpress.com/228/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/alexreg.wordpress.com/228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/alexreg.wordpress.com/228/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/alexreg.wordpress.com/228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/alexreg.wordpress.com/228/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/alexreg.wordpress.com/228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/alexreg.wordpress.com/228/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/alexreg.wordpress.com/228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/alexreg.wordpress.com/228/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/alexreg.wordpress.com/228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/alexreg.wordpress.com/228/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/alexreg.wordpress.com/228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/alexreg.wordpress.com/228/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=alexreg.wordpress.com&amp;blog=3367172&amp;post=228&amp;subd=alexreg&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://alexreg.wordpress.com/2009/06/22/searching-for-exceptions-in-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eed60bdfc964ec62cc48aa6020a03d7b?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=PG" medium="image">
			<media:title type="html">Noldorin</media:title>
		</media:content>
	</item>
		<item>
		<title>Playlist Synchronisation for Portable Devices</title>
		<link>http://alexreg.wordpress.com/2009/06/11/playlist-synchronisation-for-portable-devices/</link>
		<comments>http://alexreg.wordpress.com/2009/06/11/playlist-synchronisation-for-portable-devices/#comments</comments>
		<pubDate>Thu, 11 Jun 2009 00:46:54 +0000</pubDate>
		<dc:creator>Noldorin</dc:creator>
				<category><![CDATA[Personal]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[audio]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[media]]></category>
		<category><![CDATA[media files]]></category>
		<category><![CDATA[media player]]></category>
		<category><![CDATA[mp3]]></category>
		<category><![CDATA[mp3 player]]></category>
		<category><![CDATA[music]]></category>
		<category><![CDATA[phone]]></category>
		<category><![CDATA[playlists]]></category>
		<category><![CDATA[portable]]></category>
		<category><![CDATA[portable device]]></category>
		<category><![CDATA[sound]]></category>
		<category><![CDATA[sync]]></category>
		<category><![CDATA[synchronisation]]></category>
		<category><![CDATA[synchronise]]></category>
		<category><![CDATA[windows media]]></category>
		<category><![CDATA[windows media player]]></category>
		<category><![CDATA[wma]]></category>
		<category><![CDATA[wmp]]></category>
		<category><![CDATA[wpl]]></category>

		<guid isPermaLink="false">http://alexreg.wordpress.com/?p=220</guid>
		<description><![CDATA[I have recently been attempting to properly set up synchronisation between Windows Media Player and my portable music player (which happens to be my phone). Though I found that the Windows Media Player synchronisation tool does the job pretty well, it does fail in one respect: it cannot copy over playlist (WPL) files. For me, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=alexreg.wordpress.com&amp;blog=3367172&amp;post=220&amp;subd=alexreg&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I have recently been attempting to properly set up synchronisation between Windows Media Player and my portable music player (which happens to be my phone). Though I found that the Windows Media Player synchronisation tool does the job pretty well, it does fail in one respect: it cannot copy over playlist (WPL) files. For me, this was a bit of a nuisance, since I rely very much on playlists to categorise my music collection.</p>
<p>The solution for me was to write my own tool that synchronises a given set of playlists with a portable device that is compatible with WMP (Windows Media Player) &#8211; as I believe many devices tend to be. The tool works simply by finding the appropiate place on the device to which to copy the playlist files (a known XML descriptor file on the device should specify this), and then copying over these files, with the locations of the media files updated to point to those on the device.</p>
<p>Naturally, my choice of technology with which to write the thing was .NET/C# &#8211; this does mean that it&#8217;s not a fully standalone application, though it does only consist of a single EXE. However, thanks to a few particularly convenient features of the language/framework (primarily LINQ to XML), the code was largely trivial to write, and the majority of the ~200 lines is in fact error handling.</p>
<p>You can <strong>download the program <a href="http://blueprintgames.com/developers/alex/misc/pps.zip">here</a>.</strong> As mentioned, it requires the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=ab99342f-5d1a-413d-8319-81da479ab0d7&amp;displaylang=en">Microsoft .NET Framework 3.5 (SP1)</a> to run, which is not installed on any current version of Windows by default, so it will need to be downloaded and installed firstly if you don&#8217;t yet have it. Also, if anyone is curious to see the code, I may be able to upload that at some point.</p>
<p>The tool should be run from the command line, and would seem to be very straightforward to use. (Run the program with no arguments to see the help information.) An example command line to syncrhonise the playlists in the standard location of your user profile with a portable device on drive <em>F</em> might be:</p>
<p><em>pps F &#8220;C:\Users\username\Music\Playlists&#8221;</em></p>
<p>That&#8217;s all it takes. The task should finish within a matter of seconds  and then report some general information about the playlists it found and what it managed to successfully synchronised; else return an error message.</p>
<p><em>NB: If you&#8217;re wondering how the synchroniser matches the media files on the device with those in the playlist, I have a small admission to make. Because the directory structure is not guaranteed to be the same on the device as at the location of the source media, the current version simply matches media items by file name. This works perfectly well for me, though there is clearly a caveat. I am looking for an improvement on this method, and while I have a few ideas, I haven&#8217;t finalised my decision yet. Any recommendations by someone more knowledgeable on the subject would be appreciated.</em></p>
<p>Now, this program was designed primarily for my own use, but I did consciously attempt to make it usable with any WMP-compatible portable device, so hopefully people shouldn&#8217;t have any major problems using it.</p>
<p>Finally, it would be nice to hear any feedback regarding this little tool of mine, so please feel free to drop me a message (even if it&#8217;s just to say you&#8217;re using it). If I hear any suggestion for a worthwhile feature to add (or of course a valid bug report), I will gladly update the program.</p>
<br />Posted in Personal, Projects, Software Tagged: .net, audio, c#, media, media files, media player, mp3, mp3 player, music, phone, playlists, portable, portable device, sound, sync, synchronisation, synchronise, windows media, windows media player, wma, wmp, wpl <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/alexreg.wordpress.com/220/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/alexreg.wordpress.com/220/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/alexreg.wordpress.com/220/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/alexreg.wordpress.com/220/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/alexreg.wordpress.com/220/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/alexreg.wordpress.com/220/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/alexreg.wordpress.com/220/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/alexreg.wordpress.com/220/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/alexreg.wordpress.com/220/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/alexreg.wordpress.com/220/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/alexreg.wordpress.com/220/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/alexreg.wordpress.com/220/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/alexreg.wordpress.com/220/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/alexreg.wordpress.com/220/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=alexreg.wordpress.com&amp;blog=3367172&amp;post=220&amp;subd=alexreg&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://alexreg.wordpress.com/2009/06/11/playlist-synchronisation-for-portable-devices/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eed60bdfc964ec62cc48aa6020a03d7b?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=PG" medium="image">
			<media:title type="html">Noldorin</media:title>
		</media:content>
	</item>
		<item>
		<title>Code Golf: Evaluating Mathematical Expressions</title>
		<link>http://alexreg.wordpress.com/2009/05/30/code-golf-evaluating-mathematical-expressions/</link>
		<comments>http://alexreg.wordpress.com/2009/05/30/code-golf-evaluating-mathematical-expressions/#comments</comments>
		<pubDate>Sat, 30 May 2009 21:56:19 +0000</pubDate>
		<dc:creator>Noldorin</dc:creator>
				<category><![CDATA[Fun]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[addition]]></category>
		<category><![CDATA[arithmetic]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[code golf]]></category>
		<category><![CDATA[division]]></category>
		<category><![CDATA[expression]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[mathematical expression]]></category>
		<category><![CDATA[maths]]></category>
		<category><![CDATA[multiplication]]></category>
		<category><![CDATA[operators]]></category>
		<category><![CDATA[parsing]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[regex]]></category>
		<category><![CDATA[stackoverflow]]></category>
		<category><![CDATA[subtraction]]></category>
		<category><![CDATA[text parsing]]></category>

		<guid isPermaLink="false">http://alexreg.wordpress.com/?p=204</guid>
		<description><![CDATA[Yesterday I happened to stumble across a code golf question and for no particular reason (except for perhaps boredom) decided to create my own problem and to post it on StackOverflow for the community to reply with their solutions. It actually turned out to be much more popular than I might have anticipated. A quick [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=alexreg.wordpress.com&amp;blog=3367172&amp;post=204&amp;subd=alexreg&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Yesterday I happened to stumble across a <em>code golf</em> question and for no particular reason (except for perhaps boredom) decided to create my own problem and <a href="http://stackoverflow.com/questions/928563/code-golf-evaluating-mathematical-expressions">to post it on StackOverflow</a> for the community to reply with their solutions. It actually turned out to be much more popular than I might have anticipated.</p>
<p>A quick definition of <em>code golf</em> for those who are unaware of this enormous (though really quite enjoyable) time sink:</p>
<blockquote><p>The objective of code golf is simply to write a program/function that solves a given problem using the fewest possible number of characters. This usually involves clever tricks related to the problem and whatever language you use, followed by heavy obfuscation.</p></blockquote>
<p>Here is the problem specification, copied from my StackOverflow post:</p>
<blockquote><p>Write a function that takes a single   argument that is a   string representation of a simple   mathematical expression and evaluates   it as a floating point value. A   &#8220;simple expression&#8221; may include any of   the following: positive or negative   decimal numbers, <strong>+</strong>, <strong>-</strong>, <strong>*</strong>, <strong>/</strong>, <strong>(</strong>, <strong>)</strong>.   Expressions use (normal) <a rel="nofollow" href="http://en.wikipedia.org/wiki/Infix%5Fnotation">infix notation</a>.   Operators should be evaluated in the   order they appear, i.e. <em>not</em> as in   <a rel="nofollow" href="http://en.wikipedia.org/wiki/BODMAS">BODMAS</a>,   though brackets should be correctly   observed, of course. The function should return   the correct result for <em>any</em> possible expression   of this form. However, the function does not have   to handle malformed expressions (i.e. ones with bad syntax).</p>
<p>Examples of expressions:</p>
<pre><span>1</span><span> </span><span>+</span><span> </span><span>3</span><span> </span><span>/</span><span> </span><span>-</span><span>8</span><span>                            </span><span>=</span><span> </span><span>-</span><span>0.5</span><span>       </span><span>(</span><span>No</span><span> BODMAS</span><span>)</span><span>
</span><span>2</span><span>*</span><span>3</span><span>*</span><span>4</span><span>*</span><span>5</span><span>+</span><span>99</span><span>                            </span><span>=</span><span> </span><span>219</span><span>
</span><span>4</span><span> </span><span>*</span><span> </span><span>(</span><span>9</span><span> </span><span>-</span><span> </span><span>4</span><span>)</span><span> </span><span>/</span><span> </span><span>(</span><span>2</span><span> </span><span>*</span><span> </span><span>6</span><span> </span><span>-</span><span> </span><span>2</span><span>)</span><span> </span><span>+</span><span> </span><span>8</span><span>         </span><span>=</span><span> </span><span>10</span><span>
</span><span>1</span><span> </span><span>+</span><span> </span><span>((</span><span>123</span><span> </span><span>*</span><span> </span><span>3</span><span> </span><span>-</span><span> </span><span>69</span><span>)</span><span> </span><span>/</span><span> </span><span>100</span><span>)</span><span>            </span><span>=</span><span> </span><span>4</span><span>
</span><span>2.45</span><span>/</span><span>8.5</span><span>*</span><span>9.27</span><span>+(</span><span>5</span><span>*</span><span>0.0023</span><span>)</span><span>              </span><span>=</span><span> </span><span>2.68</span><span>...</span><span>
</span></pre>
</blockquote>
<p>Now, my own solution isn&#8217;t particularly astounding, but I did get it down to <strong>403 characters</strong>, and have since cut off a few more (though haven&#8217;t bothered to re-obfuscate it). It is in fact my first proper attempt at code golf, so I don&#8217;t consider it too bad.</p>
<p>Here it is, in all its obfuscated ugliness:</p>
<pre class="csharp" style="font-family:monospace;color:#006;border:1px solid #d0d0d0;background-color:#f0f0f0;white-space:pre-wrap;margin-bottom:1em;"><span style="color:#FF0000;">float</span> e<span style="color:#000000;">(</span><span style="color:#FF0000;">string</span> x<span style="color:#000000;">)</span><span style="color:#000000;">{</span><span style="color:#FF0000;">float</span> v<span style="color:#008000;">=</span><span style="color:#FF0000;">0</span><span style="color:#008000;">;</span>if<span style="color:#000000;">(</span><span style="color:#FF0000;">float</span>.<span style="color:#0000FF;">TryParse</span><span style="color:#000000;">(</span>x,<span style="color:#0600FF;">out</span> v<span style="color:#000000;">)</span><span style="color:#000000;">)</span><span style="color:#0600FF;">return</span> v<span style="color:#008000;">;</span>x<span style="color:#008000;">+=</span><span style="color:#666666;">';'</span><span style="color:#008000;">;</span>int t<span style="color:#008000;">=</span><span style="color:#FF0000;">0</span><span style="color:#008000;">;</span><span style="color:#FF0000;">char</span> o,s<span style="color:#008000;">=</span><span style="color:#666666;">'?'</span>,p<span style="color:#008000;">=</span><span style="color:#666666;">'+'</span><span style="color:#008000;">;</span>float n<span style="color:#008000;">=</span><span style="color:#FF0000;">0</span><span style="color:#008000;">;</span>int l<span style="color:#008000;">=</span><span style="color:#FF0000;">0</span><span style="color:#008000;">;</span>for<span style="color:#000000;">(</span><span style="color:#FF0000;">int</span> i<span style="color:#008000;">=</span><span style="color:#FF0000;">0</span><span style="color:#008000;">;</span>i<span style="color:#008000;">&lt;</span>x.<span style="color:#0000FF;">Length</span><span style="color:#008000;">;</span>i<span style="color:#008000;">++</span><span style="color:#000000;">)</span><span style="color:#000000;">{</span>o<span style="color:#008000;">=</span>s<span style="color:#008000;">;</span>if<span style="color:#000000;">(</span>
x<span style="color:#000000;">[</span>i<span style="color:#000000;">]</span><span style="color:#008000;">!=</span><span style="color:#666666;">' '</span><span style="color:#000000;">)</span><span style="color:#000000;">{</span>s<span style="color:#008000;">=</span>x<span style="color:#000000;">[</span>i<span style="color:#000000;">]</span><span style="color:#008000;">;</span>if<span style="color:#000000;">(</span><span style="color:#FF0000;">char</span>.<span style="color:#0000FF;">IsDigit</span><span style="color:#000000;">(</span>x<span style="color:#000000;">[</span>i<span style="color:#000000;">]</span><span style="color:#000000;">)</span><span style="color:#008000;">|</span>s<span style="color:#008000;">==</span><span style="color:#666666;">'.'</span><span style="color:#008000;">|</span><span style="color:#000000;">(</span>s<span style="color:#008000;">==</span><span style="color:#666666;">'-'</span><span style="color:#008000;">&amp;</span>o<span style="color:#008000;">!=</span><span style="color:#666666;">'1'</span><span style="color:#000000;">)</span><span style="color:#000000;">)</span>s<span style="color:#008000;">=</span><span style="color:#666666;">'1'</span><span style="color:#008000;">;</span>if<span style="color:#000000;">(</span>s<span style="color:#008000;">==</span><span style="color:#666666;">')'</span><span style="color:#000000;">)</span>
l<span style="color:#008000;">--;</span>if<span style="color:#000000;">(</span>s<span style="color:#008000;">!=</span>o<span style="color:#008000;">&amp;</span>l<span style="color:#008000;">==</span>0<span style="color:#000000;">)</span><span style="color:#000000;">{</span><span style="color:#0600FF;">if</span><span style="color:#000000;">(</span>o<span style="color:#008000;">==</span><span style="color:#666666;">'1'</span><span style="color:#008000;">|</span>o<span style="color:#008000;">==</span><span style="color:#666666;">')'</span><span style="color:#000000;">)</span><span style="color:#000000;">{</span>n<span style="color:#008000;">=</span>e<span style="color:#000000;">(</span>x.<span style="color:#0000FF;">Substring</span><span style="color:#000000;">(</span>t,i<span style="color:#008000;">-</span>t<span style="color:#000000;">)</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>if<span style="color:#000000;">(</span>p<span style="color:#008000;">==</span><span style="color:#666666;">'+'</span><span style="color:#000000;">)</span>v<span style="color:#008000;">+=</span>n<span style="color:#008000;">;</span>
<span style="color:#0600FF;">if</span><span style="color:#000000;">(</span>p<span style="color:#008000;">==</span><span style="color:#666666;">'-'</span><span style="color:#000000;">)</span>v<span style="color:#008000;">-=</span>n<span style="color:#008000;">;</span>if<span style="color:#000000;">(</span>p<span style="color:#008000;">==</span><span style="color:#666666;">'*'</span><span style="color:#000000;">)</span>v<span style="color:#008000;">*=</span>n<span style="color:#008000;">;</span>if<span style="color:#000000;">(</span>p<span style="color:#008000;">==</span><span style="color:#666666;">'/'</span><span style="color:#000000;">)</span>v<span style="color:#008000;">/=</span>n<span style="color:#008000;">;</span>p<span style="color:#008000;">=</span>x<span style="color:#000000;">[</span>i<span style="color:#000000;">]</span><span style="color:#008000;">;</span><span style="color:#000000;">}</span>t<span style="color:#008000;">=</span>i<span style="color:#008000;">;</span>if<span style="color:#000000;">(</span>s<span style="color:#008000;">==</span><span style="color:#666666;">'('</span><span style="color:#000000;">)</span>t<span style="color:#008000;">++;</span><span style="color:#000000;">}</span>
<span style="color:#0600FF;">if</span><span style="color:#000000;">(</span>s<span style="color:#008000;">==</span><span style="color:#666666;">'('</span><span style="color:#000000;">)</span>l<span style="color:#008000;">++;</span><span style="color:#000000;">}</span><span style="color:#000000;">}</span><span style="color:#0600FF;">return</span> v<span style="color:#008000;">;</span><span style="color:#000000;">}</span></pre>
<p>And in a rather more readable form (identical in behaviour):</p>
<pre class="csharp" style="font-family:monospace;color:#006;border:1px solid #d0d0d0;background-color:#f0f0f0;max-height:40em;overflow:auto;margin-bottom:1em;"><span style="color:#FF0000;">float</span> Eval<span style="color:#000000;">(</span><span style="color:#FF0000;">string</span> expr<span style="color:#000000;">)</span>
<span style="color:#000000;">{</span>
    <span style="color:#FF0000;">float</span> val <span style="color:#008000;">=</span> <span style="color:#FF0000;">0</span><span style="color:#008000;">;</span>
    <span style="color:#0600FF;">if</span> <span style="color:#000000;">(</span><span style="color:#FF0000;">float</span>.<span style="color:#0000FF;">TryParse</span><span style="color:#000000;">(</span>expr, <span style="color:#0600FF;">out</span> val<span style="color:#000000;">)</span><span style="color:#000000;">)</span>
        <span style="color:#0600FF;">return</span> val<span style="color:#008000;">;</span>
    expr <span style="color:#008000;">+=</span> <span style="color:#666666;">';'</span><span style="color:#008000;">;</span>
    <span style="color:#FF0000;">int</span> tokenStart <span style="color:#008000;">=</span> <span style="color:#FF0000;">0</span><span style="color:#008000;">;</span>
    <span style="color:#FF0000;">char</span> oldState, state <span style="color:#008000;">=</span> <span style="color:#666666;">'?'</span>, op <span style="color:#008000;">=</span> <span style="color:#666666;">'+'</span><span style="color:#008000;">;</span>
    <span style="color:#FF0000;">float</span> num <span style="color:#008000;">=</span> <span style="color:#FF0000;">0</span><span style="color:#008000;">;</span>
    <span style="color:#FF0000;">int</span> level <span style="color:#008000;">=</span> <span style="color:#FF0000;">0</span><span style="color:#008000;">;</span>
    <span style="color:#0600FF;">for</span> <span style="color:#000000;">(</span><span style="color:#FF0000;">int</span> i <span style="color:#008000;">=</span> <span style="color:#FF0000;">0</span><span style="color:#008000;">;</span> i <span style="color:#008000;">&lt;</span> expr.<span style="color:#0000FF;">Length</span><span style="color:#008000;">;</span> i<span style="color:#008000;">++</span><span style="color:#000000;">)</span>
    <span style="color:#000000;">{</span>
        oldState <span style="color:#008000;">=</span> state<span style="color:#008000;">;</span>
        <span style="color:#0600FF;">if</span> <span style="color:#000000;">(</span>expr<span style="color:#000000;">[</span>i<span style="color:#000000;">]</span> <span style="color:#008000;">!=</span> <span style="color:#666666;">' '</span><span style="color:#000000;">)</span>
        <span style="color:#000000;">{</span>
            state <span style="color:#008000;">=</span> expr<span style="color:#000000;">[</span>i<span style="color:#000000;">]</span><span style="color:#008000;">;</span>
            <span style="color:#0600FF;">if</span> <span style="color:#000000;">(</span><span style="color:#FF0000;">char</span>.<span style="color:#0000FF;">IsDigit</span><span style="color:#000000;">(</span>expr<span style="color:#000000;">[</span>i<span style="color:#000000;">]</span><span style="color:#000000;">)</span> <span style="color:#008000;">||</span> state <span style="color:#008000;">==</span> <span style="color:#666666;">'.'</span> <span style="color:#008000;">||</span>
                <span style="color:#000000;">(</span>state <span style="color:#008000;">==</span> <span style="color:#666666;">'-'</span> <span style="color:#008000;">&amp;&amp;</span> oldState <span style="color:#008000;">!=</span> <span style="color:#666666;">'1'</span><span style="color:#000000;">)</span><span style="color:#000000;">)</span>
                state <span style="color:#008000;">=</span> <span style="color:#666666;">'1'</span><span style="color:#008000;">;</span>
            <span style="color:#0600FF;">if</span> <span style="color:#000000;">(</span>state <span style="color:#008000;">==</span> <span style="color:#666666;">')'</span><span style="color:#000000;">)</span>
                level<span style="color:#008000;">--;</span>
            <span style="color:#0600FF;">if</span> <span style="color:#000000;">(</span>state <span style="color:#008000;">!=</span> oldState <span style="color:#008000;">&amp;&amp;</span> level <span style="color:#008000;">==</span> 0<span style="color:#000000;">)</span>
            <span style="color:#000000;">{</span>
                <span style="color:#0600FF;">if</span> <span style="color:#000000;">(</span>oldState <span style="color:#008000;">==</span> <span style="color:#666666;">'1'</span> <span style="color:#008000;">||</span> oldState <span style="color:#008000;">==</span> <span style="color:#666666;">')'</span><span style="color:#000000;">)</span>
                <span style="color:#000000;">{</span>
                    num <span style="color:#008000;">=</span> Eval<span style="color:#000000;">(</span>expr.<span style="color:#0000FF;">Substring</span><span style="color:#000000;">(</span>tokenStart, i <span style="color:#008000;">-</span> tokenStart<span style="color:#000000;">)</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
                    <span style="color:#0600FF;">if</span> <span style="color:#000000;">(</span>op <span style="color:#008000;">==</span> <span style="color:#666666;">'+'</span><span style="color:#000000;">)</span> val <span style="color:#008000;">+=</span> num<span style="color:#008000;">;</span>
                    <span style="color:#0600FF;">if</span> <span style="color:#000000;">(</span>op <span style="color:#008000;">==</span> <span style="color:#666666;">'-'</span><span style="color:#000000;">)</span> val <span style="color:#008000;">-=</span> num<span style="color:#008000;">;</span>
                    <span style="color:#0600FF;">if</span> <span style="color:#000000;">(</span>op <span style="color:#008000;">==</span> <span style="color:#666666;">'*'</span><span style="color:#000000;">)</span> val <span style="color:#008000;">*=</span> num<span style="color:#008000;">;</span>
                    <span style="color:#0600FF;">if</span> <span style="color:#000000;">(</span>op <span style="color:#008000;">==</span> <span style="color:#666666;">'/'</span><span style="color:#000000;">)</span> val <span style="color:#008000;">/=</span> num<span style="color:#008000;">;</span>
                    op <span style="color:#008000;">=</span> expr<span style="color:#000000;">[</span>i<span style="color:#000000;">]</span><span style="color:#008000;">;</span>
                <span style="color:#000000;">}</span>
                tokenStart <span style="color:#008000;">=</span> i<span style="color:#008000;">;</span>
                <span style="color:#0600FF;">if</span> <span style="color:#000000;">(</span>state <span style="color:#008000;">==</span> <span style="color:#666666;">'('</span><span style="color:#000000;">)</span>
                    tokenStart<span style="color:#008000;">++;</span>
            <span style="color:#000000;">}</span>
            <span style="color:#0600FF;">if</span> <span style="color:#000000;">(</span>state <span style="color:#008000;">==</span> <span style="color:#666666;">'('</span><span style="color:#000000;">)</span>
                level<span style="color:#008000;">++;</span>
        <span style="color:#000000;">}</span>
    <span style="color:#000000;">}</span>
    <span style="color:#0600FF;">return</span> val<span style="color:#008000;">;</span>
<span style="color:#000000;">}</span></pre>
<p>The current leading solution in one written in Haskell (a mere 226 chars), with another in Python (237 chars) taking second place. This hardly surprises me &#8211; the functional and dynamic languages almost inevitably have more succinct syntax, besides generally being known to be more suitable for creating parsers. (If I hadn&#8217;t specified the absence of the BODMAS rules, I would have surely seen a solution containing little more than an <em>&#8220;</em>eval&#8221; statement!) Interestingly, the top two have both managed to avoid using regex altogether (though other solutions have with some success). In my opinion, it&#8217;s worth reading through the question to see how the various languages compare at performing the same task.</p>
<p>Please feel free to reply to the StackOverflow question or this post if you have a unique solution (in any language) that you&#8217;d like to share.</p>
<h3>Update</h3>
<p>I ended up spending just a bit longer on this task, since having seen some of the other solutions, it became pretty clear that I could get the char count down a good deal more. With the help of regex, <a href="http://stackoverflow.com/questions/928563/code-golf-evaluating-mathematical-expressions/944716#944716">my new solution</a> stands at <strong>294 characters</strong>. That in fact seems to be the winner amongst the set of solutions in C-style languages, so I&#8217;m quite pleased. (I have now promised myself not to entertain myself any long with this game, however.)</p>
<p>Here it is in a (relatively) clear form, in case anyone&#8217;s interested. (It assumes the <em>System.Text.RegularExpressions</em> namespace has been imported.)</p>
<pre class="csharp" style="font-family:monospace;color:#006;border:1px solid #d0d0d0;background-color:#f0f0f0;margin-bottom:1em;"><span style="color:#FF0000;">float</span> e<span style="color:#000000;">(</span><span style="color:#FF0000;">string</span> x<span style="color:#000000;">)</span>
<span style="color:#000000;">{</span>
    <span style="color:#0600FF;">while</span> <span style="color:#000000;">(</span>x.<span style="color:#0000FF;">Contains</span><span style="color:#000000;">(</span><span style="color:#666666;">"("</span><span style="color:#000000;">)</span><span style="color:#000000;">)</span>
        x <span style="color:#008000;">=</span> Regex.<span style="color:#0000FF;">Replace</span><span style="color:#000000;">(</span>x, <span style="color:#666666;">@"\(([^\(]*?)\)"</span>, m <span style="color:#008000;">=&gt;</span> e<span style="color:#000000;">(</span>m.<span style="color:#0000FF;">Groups</span><span style="color:#000000;">[</span>1<span style="color:#000000;">]</span>.<span style="color:#0000FF;">Value</span><span style="color:#000000;">)</span>.<span style="color:#0000FF;">ToString</span><span style="color:#000000;">(</span><span style="color:#000000;">)</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>

    <span style="color:#FF0000;">float</span> r <span style="color:#008000;">=</span> <span style="color:#FF0000;">0</span><span style="color:#008000;">;</span>
    <span style="color:#0600FF;">foreach</span> <span style="color:#000000;">(</span>Match m <span style="color:#0600FF;">in</span> Regex.<span style="color:#0000FF;">Matches</span><span style="color:#000000;">(</span><span style="color:#666666;">"+"</span> <span style="color:#008000;">+</span> x, <span style="color:#666666;">@"\D ?-?[\d.]+"</span><span style="color:#000000;">)</span><span style="color:#000000;">)</span>
    <span style="color:#000000;">{</span>
        var o <span style="color:#008000;">=</span> m.<span style="color:#0000FF;">Value</span><span style="color:#000000;">[</span>0<span style="color:#000000;">]</span><span style="color:#008000;">;</span>
        var v <span style="color:#008000;">=</span> <span style="color:#FF0000;">float</span>.<span style="color:#0000FF;">Parse</span><span style="color:#000000;">(</span>m.<span style="color:#0000FF;">Value</span>.<span style="color:#0000FF;">Substring</span><span style="color:#000000;">(</span>1<span style="color:#000000;">)</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
        r <span style="color:#008000;">=</span> o <span style="color:#008000;">==</span> <span style="color:#666666;">'+'</span> <span style="color:#008000;">?</span> r <span style="color:#008000;">+</span> v <span style="color:#008000;">:</span> o <span style="color:#008000;">==</span> <span style="color:#666666;">'-'</span> <span style="color:#008000;">?</span> r <span style="color:#008000;">-</span> v <span style="color:#008000;">:</span> o <span style="color:#008000;">==</span> <span style="color:#666666;">'*'</span> <span style="color:#008000;">?</span> r <span style="color:#008000;">*</span> v <span style="color:#008000;">:</span> r <span style="color:#008000;">/</span> v<span style="color:#008000;">;</span>
    <span style="color:#000000;">}</span>
    <span style="color:#0600FF;">return</span> r<span style="color:#008000;">;</span>
<span style="color:#000000;">}</span></pre>
<div id="_mcePaste" style="overflow:hidden;position:absolute;left:-10000px;top:594px;width:1px;height:1px;">http://stackoverflow.com/questions/928563/code-golf-evaluating-mathematical-expressions/944716#944716</div>
<br />Posted in Fun, Programming Tagged: addition, arithmetic, c#, code golf, division, expression, haskell, math, mathematical expression, maths, multiplication, operators, parsing, python, regex, stackoverflow, subtraction, text parsing <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/alexreg.wordpress.com/204/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/alexreg.wordpress.com/204/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/alexreg.wordpress.com/204/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/alexreg.wordpress.com/204/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/alexreg.wordpress.com/204/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/alexreg.wordpress.com/204/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/alexreg.wordpress.com/204/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/alexreg.wordpress.com/204/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/alexreg.wordpress.com/204/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/alexreg.wordpress.com/204/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/alexreg.wordpress.com/204/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/alexreg.wordpress.com/204/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/alexreg.wordpress.com/204/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/alexreg.wordpress.com/204/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=alexreg.wordpress.com&amp;blog=3367172&amp;post=204&amp;subd=alexreg&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://alexreg.wordpress.com/2009/05/30/code-golf-evaluating-mathematical-expressions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eed60bdfc964ec62cc48aa6020a03d7b?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=PG" medium="image">
			<media:title type="html">Noldorin</media:title>
		</media:content>
	</item>
		<item>
		<title>Circular Buffer for .NET</title>
		<link>http://alexreg.wordpress.com/2009/05/23/circular-buffer-for-net/</link>
		<comments>http://alexreg.wordpress.com/2009/05/23/circular-buffer-for-net/#comments</comments>
		<pubDate>Sat, 23 May 2009 01:07:40 +0000</pubDate>
		<dc:creator>Noldorin</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[buffer]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[c# 3.0]]></category>
		<category><![CDATA[circular buffer]]></category>
		<category><![CDATA[collections]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[i/o]]></category>
		<category><![CDATA[icollection]]></category>
		<category><![CDATA[ienumerable]]></category>
		<category><![CDATA[memory stream]]></category>
		<category><![CDATA[ring buffer]]></category>
		<category><![CDATA[stream]]></category>

		<guid isPermaLink="false">http://alexreg.wordpress.com/?p=200</guid>
		<description><![CDATA[This is a quick announcement that I&#8217;ve released my code for an implementation of a generic circular buffer for .NET (written in C# 3.0). The release also includes an implementation of a circular stream, which is a wrapper over a circular buffer of bytes. You can view the project and download the source code over [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=alexreg.wordpress.com&amp;blog=3367172&amp;post=200&amp;subd=alexreg&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This is a quick announcement that I&#8217;ve released my code for an implementation of a generic <a href="http://en.wikipedia.org/wiki/Circular_buffer">circular buffer</a> for .NET (written in C# 3.0). The release also includes an implementation of a circular stream, which is a wrapper over a circular buffer of bytes. You can <a href="http://circularbuffer.codeplex.com/">view the project</a> and <a href="http://circularbuffer.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=27751">download the source code</a> over at CodePlex, where I&#8217;ve licensed it under the MS-PL, which should hopefully be fairly unrestrictive.</p>
<p>If you&#8217;re wondering where this idea came from, I recently came across an interesting use for a circular buffer, and upon finding out that the .NET BCL contained nothing along the lines of a circular buffer (or stream), I decided to implement one myself. I&#8217;ve attempted to do everything properly of course (i.e. in the style of the BCL data structures), so hopefully it should be immediately useful to anyone familiar with the concept.</p>
<p>More about this to come later.</p>
<br />Posted in Programming Tagged: .net, buffer, c#, c# 3.0, circular buffer, collections, data structures, i/o, icollection, ienumerable, memory stream, ring buffer, stream <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/alexreg.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/alexreg.wordpress.com/200/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/alexreg.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/alexreg.wordpress.com/200/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/alexreg.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/alexreg.wordpress.com/200/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/alexreg.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/alexreg.wordpress.com/200/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/alexreg.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/alexreg.wordpress.com/200/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/alexreg.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/alexreg.wordpress.com/200/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/alexreg.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/alexreg.wordpress.com/200/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=alexreg.wordpress.com&amp;blog=3367172&amp;post=200&amp;subd=alexreg&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://alexreg.wordpress.com/2009/05/23/circular-buffer-for-net/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eed60bdfc964ec62cc48aa6020a03d7b?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=PG" medium="image">
			<media:title type="html">Noldorin</media:title>
		</media:content>
	</item>
		<item>
		<title>My Guide to Science Fiction and Fantasy</title>
		<link>http://alexreg.wordpress.com/2009/05/16/my-guide-to-sci-fi-and-fantasy/</link>
		<comments>http://alexreg.wordpress.com/2009/05/16/my-guide-to-sci-fi-and-fantasy/#comments</comments>
		<pubDate>Sat, 16 May 2009 20:31:15 +0000</pubDate>
		<dc:creator>Noldorin</dc:creator>
				<category><![CDATA[Arts]]></category>
		<category><![CDATA[Personal]]></category>
		<category><![CDATA[2001: a space odyssey]]></category>
		<category><![CDATA[arthur c. clarke]]></category>
		<category><![CDATA[baggins]]></category>
		<category><![CDATA[beowulf]]></category>
		<category><![CDATA[biology]]></category>
		<category><![CDATA[book guide]]></category>
		<category><![CDATA[book recommendations]]></category>
		<category><![CDATA[books]]></category>
		<category><![CDATA[brave new world]]></category>
		<category><![CDATA[chemistry]]></category>
		<category><![CDATA[childhood's end]]></category>
		<category><![CDATA[dune]]></category>
		<category><![CDATA[fantasy]]></category>
		<category><![CDATA[farenheit 451]]></category>
		<category><![CDATA[foundation]]></category>
		<category><![CDATA[frank herbert]]></category>
		<category><![CDATA[gandalf]]></category>
		<category><![CDATA[hard science]]></category>
		<category><![CDATA[isaac asimov]]></category>
		<category><![CDATA[j. r. r. tolkien]]></category>
		<category><![CDATA[knight of the word]]></category>
		<category><![CDATA[literature]]></category>
		<category><![CDATA[lord of the rings]]></category>
		<category><![CDATA[lotr]]></category>
		<category><![CDATA[middle earth]]></category>
		<category><![CDATA[novels]]></category>
		<category><![CDATA[ohmsford]]></category>
		<category><![CDATA[opinions]]></category>
		<category><![CDATA[physics]]></category>
		<category><![CDATA[planetary romance]]></category>
		<category><![CDATA[psychology]]></category>
		<category><![CDATA[rama]]></category>
		<category><![CDATA[rand al'thor]]></category>
		<category><![CDATA[randland]]></category>
		<category><![CDATA[rendezvous with rama]]></category>
		<category><![CDATA[robert jordan]]></category>
		<category><![CDATA[robot series]]></category>
		<category><![CDATA[robots]]></category>
		<category><![CDATA[sci-fi]]></category>
		<category><![CDATA[Science]]></category>
		<category><![CDATA[science fiction]]></category>
		<category><![CDATA[shannara]]></category>
		<category><![CDATA[silmarillion]]></category>
		<category><![CDATA[sociology]]></category>
		<category><![CDATA[soft science]]></category>
		<category><![CDATA[space odyssey]]></category>
		<category><![CDATA[space opera]]></category>
		<category><![CDATA[stanley kubrick]]></category>
		<category><![CDATA[subjective]]></category>
		<category><![CDATA[terry brooks]]></category>
		<category><![CDATA[the eye of the world]]></category>
		<category><![CDATA[the four lands]]></category>
		<category><![CDATA[the hobbit]]></category>
		<category><![CDATA[the silmarillion]]></category>
		<category><![CDATA[the wheel of time]]></category>
		<category><![CDATA[there and back again]]></category>
		<category><![CDATA[tolkien]]></category>
		<category><![CDATA[wheel of time]]></category>

		<guid isPermaLink="false">http://alexreg.wordpress.com/?p=79</guid>
		<description><![CDATA[Note: This guide is currently partially incomplete. I will try to get around to expanding the summaries at some time in the near future (in particular in the Fantasy section). Not to mention that almost undoubtedly, there will have been one or two books I will have wholly forgotten, to my future disbelief. This post [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=alexreg.wordpress.com&amp;blog=3367172&amp;post=79&amp;subd=alexreg&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>Note:</strong> This guide is currently partially incomplete. I will try to get around to expanding the summaries at some time in the near future (in particular in the Fantasy section). Not to mention that almost undoubtedly, there will have been one or two books I will have wholly forgotten, to my future disbelief.</p>
<hr />This post is a summary of my recommendations regarding fiction; specifically, in the genres of <strong>science fiction</strong> and <strong>fantasy</strong>, which have proven to be the types that have typically attracted my interest, though not quite the <em>only</em> types. Certainly, I feel that I have read enough of a variety within these areas now, that I can produce something of a useful guide for anyone interested in finding the real gems of these forms of literature. It is important to realise that the summaries that I have provided are not meant to be synopses or reviews of the books, but rather brief overviews of my personal takes on them, as well as suggestions relating to <em>why you</em> might be interested in them.</p>
<p>So without further preamble, here is my guide. I&#8217;ve listed my current favourites (by that I mean both most enjoyable and having greatest creative and literary merit) at the top, with others in a fairly arbitrary order.</p>
<h2>Science Fiction</h2>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Dune_(novel)"><strong>Dune</strong></a> and the <a href="http://en.wikipedia.org/wiki/Dune_series#Artistic_works"><strong>Dune series</strong></a> by <em>Frank Herbert</em><br />
In my opinion (and seemingly that of many others), perhaps <em>the</em> greatest science fiction novel ever written. The scope and storyline are truly unparalleled by anything else within the genre, and maybe anything else in the entire body of 20th century literature. In a certain respect, this work almost belongs within the fantasy genre because of its nature and some of the motifs &#8211; it&#8217;s much more of a superb story than superb speculative science, with a bit of philosophy thrown in. Of course, it still very much deserves the categorisation of sci-fi, mainly because of the interstellar travel (run by the monopolistic<em> </em>Spacing Guild) as well as the ecology/terraforming ideas that are involved. Overall, I might think that classifying it as a <a href="http://en.wikipedia.org/wiki/Planetary_romance">planetary romance</a> does it maximum justice, though in all fairness there&#8217;s no real way to get a decent understanding of its unique style and grand themes without reading the work in its entirity. It is certainly not so-called &#8220;hard sci-fi&#8221;, but that&#8217;s not especially what I&#8217;m interested in to be honest, and no-one who has a proper interest in literature should care either. I don&#8217;t way to say too much more about this book, since I think <em>everyone</em> with an interest in sci-fi should read this once (and preferably reread it) from a fresh perspective and to experience its wonder for themself. Now if you make it through the original <em>Dune</em> novel (I&#8217;m not sure how you can finish it and be anything less than stunned), then I would without hesistance suggest that you also pick up the second and third of the series (<em>Dune Messiah</em> and <em>Children of Dune</em>), which are excellent reads in their own rights, if not actually masterpieces. After that, I&#8217;m afraid to say that the standard of writing and storyline declines to a certain degree (with a short resurgence in the latter half of <em>Heretics of Dune</em>). The rest of it does tend to get slightly crazy (not helped by Herbert&#8217;s unusual and sometimes slightly opaque writing style), and even verges on becoming somewhat raunchy at times. Still, they are by no means poor works, albeit ones that I would only recommend to serious fans of Frank Herbert. (More precisely, they are still works of high quality, but only to a much diminished subset of people.) So that I don&#8217;t end on a seemingly sour note, I shall repeat and reinforce my statement that the the original <em>Dune</em>, written in 1965, is a piece of literature that should not be missed by anyone with an interest in speculative fiction.</li>
<li><a href="http://en.wikipedia.org/wiki/Foundation_series"><strong>Foundation series</strong></a> by <em>Isaac Asimov<br />
</em>The original <em>Foundation</em> is perhaps the first truly epic sci-fi ever created, and to some extent the precursor of <em>Dune</em> and ultimately inspirational to the <em>Star Wars</em> universe (arguably alongside <em>Dune</em> itself). Unlike Herbert&#8217;s series, however, this one peaks somewhere in the middle, with both the head and tail ends being only marginally diminished in standard. Although it may not contain a <em>single</em> book that is the equal of <em>Dune</em>, the series as a whole is probably unbeatable. Its pace and sheer scale rarely drops, and there&#8217;s always a sense of the unexpected (though a few can be predicted, Ibelieve it was intended very purposely). Again, similarly to Dune, this book is what it is because of its storyline, although there is undoubtedly a greater emphasis on the science, not surprisingly given that Asimov is in fact a scientist (chemist) by training. It contains some genuinitely interesting and imaginative scientific concepts (as well as a few strange and outdated ones, having been written in the 50s), both in terms of hard science (mainly physics and astronomy) and soft science (<a href="http://en.wikipedia.org/wiki/Psychohistory_(fictional)#Beyond_fiction">psychohistory</a> being the main one). The latter is particularly intriguing, as it demonstrates (albeit in superficial detail) an entire new branch of science, which is in essence a blend of history, sociology, and psychology turned into a mathematical study of analysis and prediction of the macro-events of the human race. As a matter of fact, I do believe that Asimov is showing some foresight in this respect. Though the level to which he proposes the usage of his psychohistory may not be very realistic, the core idea gets me thinking seriously about the possibility of such a field opening up in the future. To summarise, he explores a number of both scientific an human themes with exceptional insight, yet some amount of subtlety too. So if you want something that is enormous in scope, besides superb entertainment (yes, these novels even include a bit of humour!), you assuredly cannot go wrong with this series.</li>
<li><a href="http://en.wikipedia.org/wiki/Space_Odyssey"><strong>Space Odyssey series</strong></a> by <em>Arthur C. Clarke<br />
2001: A Space Odyssey</em> was one of the first proper science fiction novels I read (as a young teenager), and probably what really grabbed my fascination with the genre. As a novel written alongside a (faithful) film script, the storyline in fact ended up producing both a fantastic book and film, and counts for much of what made the Clarke the celebrity he was. Sadly, the great author passed away less than a year ago now, though he continued to write with much of his former skill well into the 21st century. Clarke&#8217;s works have always had the tendency to focus on space, the universe, and other intelligent species, and though they are perhaps not as grand in style as <em>Dune</em> or <em>Foundation</em> (he is clearly a realist opposed to the more romantic styles of the other two authors), they do have astoundingly good (hard) science, as well an undeniable element of suspense, which is present throughout almost all of his creations. The <em>Space Odyssey </em>series as a whole is one definitely worth reading to the end. If I remember rightly, only one of the four in the series (the others have the same names, replaced by the years 2010, 2061, and 3001) is a <em>slight</em> letdown, though the remainder (importantly, including the first and the last) are most enjoyable indeed. The first of the series I must however single out and include among my &#8220;big three&#8221; of sci-fi, the others being the original dune <em>Dune</em> and <em>Foundation</em> (despite a number of excellent sequels), as you might have suspected by now.</li>
<li><a href="http://en.wikipedia.org/wiki/Rendezvous_with_Rama"><strong>Rendezvous with Rama</strong></a> and the <strong>Rama series</strong> by <em>Arthur C. Clarke<br />
</em>Belonging almost as much in mystery/thriller category as it does in science fiction, it is nevertheless an astonishing read. The highly unique view that this story offers in relating the first contact of humans with other intelligent life (of a much more advanced form in this case) may not be an especially grand one, but the imagination that went into this creation was surely immense. Being a mystery, I&#8217;m not going to comment any more about the book, even in vague terms. (Or maybe I&#8217;m just not too sure what to think of it as a whole.) Specifically, I would recommend that if your introduction to the works of Arthur C. Clarke is (or has already been) a pleasant one beginning with with <em>2001: A Space Odyssey</em>, then this should definitely be next thing on your reading list. Most unfortunately however, akin to the <em>Dune</em> series, the quality of successive books  does deteriorate a certain amount. (I can confidently say that the second is worth a read, though, while the subsequent ones lose some, if not all, of their novelty.) If you need any more convincing, let me point out that <em>Rendezvous with Rama</em> won both of the highest commendations in science fiction, the <a href="http://en.wikipedia.org/wiki/Hugo_Award">Hugo Award</a> and the <a href="http://en.wikipedia.org/wiki/Nebula_Award">Nebula Award</a>, a feat that<em> </em>the original <em>Dune</em> similarly achieved.</li>
<li><a href="http://en.wikipedia.org/wiki/Brave_new_world"><strong>Brave New World</strong></a> by <em>Aldous Huxley</em><br />
Who hasn&#8217;t heard of this work alongside <em>The War of the Worlds</em> as a prime example of classic science fiction? Again, not celebrated so much for its scientific content as the eloquent manner in which it conveys certain philosophical and speculative ideas. I won&#8217;t deny that this is a bit of a depressing read in some ways, but its philosophical and socilogical implications are beyond doubt not only captivating but also quite relevant to modern society. Perhaps I do have something of a penchant for philosophical prophecy in literature, but I don&#8217;t think anyone can finish this book not having had their own thoughts and outlook on life and society sincerely provoked, if not disturbed by this powerful portrayal of a dystopian world in the near future.</li>
<li><a href="http://en.wikipedia.org/wiki/Fahrenheit_451"><strong>Farennheit 451</strong></a> by <em>Ray Bradbury</em><br />
A curious title, let alone book, and perhaps science fiction is not the most obvious classification for this work, though I think in a sociological sense it is so speculative and strikingly relevant regarding our future that it should be deemed so. This book has many parallels with Brave New World, the evident ones being the examination of dystopian societies (albeit two different forms) and philosophical warnings with undeniable precautionary overtones. They are both surely championing the freedom of independent thought and behaviour over the horrors that extreme conformism might bring. And finally: a book about the destruction of books &#8211; is there not a wonderful irony (perhaps even mockery) in this predominant theme?</li>
</ul>
<p>There are additionally a few books about which I have heard very positive reports but unfortunately haven&#8217;t gotten around to reading yet. I&#8217;ll update the summaries when I do get around to reading at least some of these books, which will most probably be some time over the coming summer break.</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Childhood%27s_End"><strong>Childhood&#8217;s End</strong></a> by <em>Arthur C. Clarke</em><br />
[Summary to come.]</li>
<li>The <a href="http://en.wikipedia.org/wiki/Isaac_Asimov%27s_Robot_Series"><strong>Robot series</strong></a> by <em>Isaac Asimov</em><br />
[Summary to come.] For the time being, maybe pointing out that the film <em>I, Robot</em> was based on Asimov&#8217;s book of the same name will be enough to convince some to read it?</li>
</ul>
<h2>Fantasy</h2>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Lord_of_the_rings"><strong>The Lord of the Rings</strong></a> trilogy and <strong><a href="http://en.wikipedia.org/wiki/The_hobbit">The Hobbit, or There and Back Again</a></strong> by <em>J.R.R. Tolkien<br />
</em>How much do I need to say about this one? That it most likely surpasses all of the others in both of the categories I have listed here should say enough about my particularly high opinion of the works. (I am a self-confessed Tolkien fanatic, after all)<em> </em>In fact, if you need convincing to read this epic, then I would suggest that you stop reading this list now (not that I would have expected you to get this far anyway)!<em> </em>I&#8217;ve mainly just included this entry for completeness, not because it&#8217;s going to be of any supreme help to anyone<em>. </em>As a side note, <em>The Hobbit, or There and Back Again</em> (commonly simply referred to as <em>The Hobbit</em>)<em> </em>should without doubt be read alongside the trilogy &#8211; whether before or after ought not make much of a difference to its impact, at least as I see it. Though I&#8217;m not sure to what extent this perception exists, I will nonetheless suggest that you dispell all notions of this being a story for chlidren &#8211; indeed it is no less suitable for adults than it is for a child, despite its comparative light-heartedness, which has possibly given it such a reputation. While I, as many others, read the novel first when I was quite young, it has not since lost its endearing quality to me, and see no reason why it should for anyone else.</li>
<li><a href="http://en.wikipedia.org/wiki/The_Silmarillion"><strong>The Silmarillion</strong></a> by <em>J.R.R. Tolkien<br />
</em>The epic historical prequel to <em>The Hobbit</em> and <em>The Lord of the Rings</em>, this may not be the easiest read when you first pick it up.<em> (</em>At least, it wasn&#8217;t for me, though perhaps that was because I was much younger at the time and the somewhat archaic language didn&#8217;t help &#8211; yet I can only say it adds to the character and feeling of the story nowadays.) Nonetheless, I would argue it is almost more magnificent than <em>The Lord of the Rings</em> in certain ways, being an true archetype of epic literature. (Though I haven&#8217;t read it myself, the Anglo-Saxon poem <a href="http://en.wikipedia.org/wiki/Beowulf"><em>Beowulf</em></a> may give some impression of its style; unsurprising, given that Tolkien was a professor who taught such works of literature.) To be honest, if you&#8217;re not immeresed in it by the half-way point, then put it down, but I suspect this will not be the case for any lover of <em>The Lord of the Rings</em>, and you will hopefully become immersed as I did by the histories.</li>
<li><strong><a href="http://en.wikipedia.org/wiki/The_wheel_of_time">The Wheel of Time</a> </strong>series by <em>Robert Jordan<br />
</em>This is a series that I&#8217;ve actually not managed to finish yet. (My excuse is that it&#8217;s composed of 12 books, each ranging from roughly 700 to 1000 pages. I&#8217;m never one to race through a book or series [at least not since I was younger], and in any case I&#8217;m at least getting some enjoyment out of the reading.) Influenced to large amounts by both Tolkien and Herbert&#8217;s works (and I didn&#8217;t even know this when I started reading it!), I believe this series will given time become as renowned as those two in its own right. This is <em>the</em> series to read if you&#8217;re looking for fantasy that is both entertaining and has great <em>depth to its characters</em>, something that arguably even the great Tolkien&#8217;s works were at times missing.</li>
<li><a href="http://en.wikipedia.org/wiki/Shannara"><strong>Shannara</strong></a> series by <em>Terry Brooks<br />
</em>Shannara is Brook&#8217;s most well-known (and as of yet) unfinished series. With a total of 14 books (a set composed over individual stories and series in their own right), this beats even <em>The Wheel of Time</em> in that respect, though the fact that the various storylines are disparate to a large degree makes it significantly more manageable. Being epic high fantasy very much in the style of Tolkien (though <em>not</em> direct plagarism, as some critics were too keen to codemn <em>The Sword of Shannara</em>). In my opinion, this series needs to be read at least until the conclusion of the second book (<em>The Elfstones of the Shannara)</em>, which is in my mind still the best fantasy work outside of Tolkien&#8217;s collection, since I initially read it seven years ago.</li>
<li><a href="http://en.wikipedia.org/wiki/Word/Void"><strong>The Word and the Void</strong></a> trilogy by <em>Terry Brooks<br />
</em>This<em> </em>is Brook&#8217;s lesser known series, though in fact considered by a sizable minority to be his best writing. With a dark, modern setting, this certainly isn&#8217;t his typical style (or at least the one by which he gained his reputation), though it is perhaps his most creative composition. It is additonally notable in representing his final break-away from the influence of Tolkien (not that I can deem this a wholly undersirable event), and really includes some very original content to its plot. Even if you were turned off by Shannara (or simply not particularly impressed), I would firstly respond in shock, but then suggest that this trilogy is worth a try regardless of your opinion.</li>
</ul>
<p>Now, before some indignant <em>Harry Potter</em> fanboy comments on the absence of the series from my list (this is of course presuming I have any reading this post), I should stress that these are <em>not</em> books that have just slipped my mind. I&#8217;ve read them all (some more than once when I was a bit younger), and plainly, they are decent light entertainment, but nothing worth putting alongside the other greats, I&#8217;m afraid.</p>
<p>To end, I would only like to say that it would be very gratifying to hear whether anyone is making use of these recommendations. It would honestly be quite interesting just to gauge whether you as fellow fans of these genres concur with at least some of the views presented here, or conversely how you might view my summaries contrastingly. If not, I think I can still convince myself that I enjoyed writing this guide for its own sake!</p>
<br />Posted in Arts, Personal Tagged: 2001: a space odyssey, arthur c. clarke, baggins, beowulf, biology, book guide, book recommendations, books, brave new world, chemistry, childhood's end, dune, fantasy, farenheit 451, foundation, frank herbert, gandalf, hard science, isaac asimov, j. r. r. tolkien, knight of the word, literature, lord of the rings, lotr, middle earth, novels, ohmsford, opinions, physics, planetary romance, psychology, rama, rand al'thor, randland, rendezvous with rama, robert jordan, robot series, robots, sci-fi, Science, science fiction, shannara, silmarillion, sociology, soft science, space odyssey, space opera, stanley kubrick, subjective, terry brooks, the eye of the world, the four lands, the hobbit, the silmarillion, the wheel of time, there and back again, tolkien, wheel of time <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/alexreg.wordpress.com/79/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/alexreg.wordpress.com/79/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/alexreg.wordpress.com/79/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/alexreg.wordpress.com/79/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/alexreg.wordpress.com/79/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/alexreg.wordpress.com/79/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/alexreg.wordpress.com/79/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/alexreg.wordpress.com/79/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/alexreg.wordpress.com/79/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/alexreg.wordpress.com/79/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/alexreg.wordpress.com/79/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/alexreg.wordpress.com/79/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/alexreg.wordpress.com/79/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/alexreg.wordpress.com/79/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=alexreg.wordpress.com&amp;blog=3367172&amp;post=79&amp;subd=alexreg&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://alexreg.wordpress.com/2009/05/16/my-guide-to-sci-fi-and-fantasy/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eed60bdfc964ec62cc48aa6020a03d7b?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=PG" medium="image">
			<media:title type="html">Noldorin</media:title>
		</media:content>
	</item>
		<item>
		<title>Numerical Analysis for .NET</title>
		<link>http://alexreg.wordpress.com/2009/05/15/numerical-analysis-for-net/</link>
		<comments>http://alexreg.wordpress.com/2009/05/15/numerical-analysis-for-net/#comments</comments>
		<pubDate>Thu, 14 May 2009 23:56:18 +0000</pubDate>
		<dc:creator>Noldorin</dc:creator>
				<category><![CDATA[Personal]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[algorithms]]></category>
		<category><![CDATA[arnoldi]]></category>
		<category><![CDATA[arnoldi algorithm]]></category>
		<category><![CDATA[arpack]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[code libraries]]></category>
		<category><![CDATA[dense matrix]]></category>
		<category><![CDATA[diagonalisation]]></category>
		<category><![CDATA[dnanalytics]]></category>
		<category><![CDATA[documentation]]></category>
		<category><![CDATA[eigendecomposition]]></category>
		<category><![CDATA[eigenvalues]]></category>
		<category><![CDATA[eigenvectors]]></category>
		<category><![CDATA[f#]]></category>
		<category><![CDATA[fortran]]></category>
		<category><![CDATA[fortran77]]></category>
		<category><![CDATA[intel math kernel library]]></category>
		<category><![CDATA[intel mkl]]></category>
		<category><![CDATA[lanczos]]></category>
		<category><![CDATA[lanczos algorithm]]></category>
		<category><![CDATA[libraries]]></category>
		<category><![CDATA[linear algebra]]></category>
		<category><![CDATA[matlab]]></category>
		<category><![CDATA[matrices]]></category>
		<category><![CDATA[matrix]]></category>
		<category><![CDATA[matrix decomposition]]></category>
		<category><![CDATA[mersenne twister]]></category>
		<category><![CDATA[numerical algorithms]]></category>
		<category><![CDATA[numerical analysis]]></category>
		<category><![CDATA[open-source]]></category>
		<category><![CDATA[pseudo-random]]></category>
		<category><![CDATA[pseudorandom]]></category>
		<category><![CDATA[random number generator]]></category>
		<category><![CDATA[rng]]></category>
		<category><![CDATA[sparse matrix]]></category>
		<category><![CDATA[spectral theory]]></category>
		<category><![CDATA[stackoverflow]]></category>
		<category><![CDATA[statistical functions]]></category>
		<category><![CDATA[statistics]]></category>
		<category><![CDATA[vectors]]></category>

		<guid isPermaLink="false">http://alexreg.wordpress.com/?p=185</guid>
		<description><![CDATA[During my ongoing work on a computational project for university, I recently discovered the need to perform some serious numerical analysis from my C# code.  Unfortunately, I must admit that the .NET world only now seems to be catching up in terms of the free and open source libraries it offers for various tasks, and [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=alexreg.wordpress.com&amp;blog=3367172&amp;post=185&amp;subd=alexreg&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>During my ongoing work on a computational project for university, I recently discovered the need to perform some serious numerical analysis from my C# code.  Unfortunately, I must admit that the .NET world only now seems to be catching up in terms of the free and open source libraries it offers for various tasks, and initially I was disheartened to find that there seemed to be nothing available for doing calculations on large (sparse) matrices. After a fair deal of searching, only a couple of somewhat incomplete and no longer maintained matrix libraries turned up. Being an avid user of <a href="http://stackoverflow.com/">StackOverflow</a>, however, I decided that if anyone was aware of some library that could do what I needed, I would most likely find them there.</p>
<p>The result was much better than for what I was even hoping. <a href="http://dnanalytics.codeplex.com/">dnAnalytics</a> is a general-purpose package for numerical analysis in .NET that does almost everything for which I might possibly ask &#8211; and from my first impressions, does it very well indeed. This wonderful find is a well-maintained, fully open-source, library with great API documentation (not a wholly unexpected thing, but surprisingly uncommon among so many open source projects). There are several features that stand out as particularly impressive. One undoubtedly is <span>I/O classes for Matlab and delimited files (among other formats).</span> What is more, the library seems to offer both a fully managed version and one that wraps the<span> <a href="http://software.intel.com/en-us/intel-mkl/">Intel® Math Kernel Library</a>. I&#8217;m not sure how the performance compares between the two (I haven&#8217;t yet tried the latter), but it is surely nice to have the pair of options available, quite similarly to how you have alternatives of cryptographic algorithms in the .NET BCL, that is to say, a) a fully managed version, v) a version based on top of the Windows Crypto API, c) a version that uses the CNG (Next Generation) API introduced with Vista. Perhaps what appeals to me the greatest about this library is that the developers have clearly gone to an effort to make it user-friendly, not only with regards to the documentation, but also by adding an interface friendly to F# coders (likely to be a language of choice for future mathematical/scientific programming), and even visual debuggers for Visual Studio (possibly the only library to date I&#8217;ve seen include them).<br />
</span></p>
<p>My particular usage of the library requires me to use the linear algebra (specifically, sparse matrix) classes. Although I must point out that the specific algorithm that I was intending to employ for the project was not available (see my later discussion), it did include a host of other ones, primarily focusing on direct and iterative <a href="http://en.wikipedia.org/wiki/Matrix_decomposition">matrix decomposition</a>, which would appear to be quite handy in many circumstances. I haven&#8217;t yet had a chance to play with the other areas of the library, but I have noticed that it offers some statistical functions and methods as well as a number of modern pseudo-RNG algorithms such as the <a href="http://en.wikipedia.org/wiki/Mersenne_twister">Mersenne Twister</a>.</p>
<p>To conclude, I should come back to the point that the most important part of the analysis I require was not (at least direclty) contained by the library &#8211; finding the eigenvalues or <a href="http://en.wikipedia.org/wiki/Eigendecomposition_of_a_matrix">eigendecomposition</a> of large (1000s of rows/columns) matrices, which happens to be in relation to <a href="http://en.wikipedia.org/wiki/Spectral_theory">spectral theory</a>, in case you&#8217;re curious. Even so, being such a complex field and one fraught with difficulties when it comes to implementation (numerical instability is a huge problem), I was not surprised to find that an implementation of the <a href="http://en.wikipedia.org/wiki/Arnoldi%27s_algorithm">Arnoldi</a> or <a href="http://en.wikipedia.org/wiki/Lanczos_algorithm">Lanczos</a> algorithm was not present. Fortunately, after a bit more searching around (by this point I knew specifically what I was looking for), I came across the <a href="http://www.caam.rice.edu/software/ARPACK/">ARPACK</a> library, written in the archaic Fortran77 language. It did however seem to be <em>exactly</em> what I was looking for: a set of fast routines to find the eigenvalues of large (either dense or sparse) matrices of various types. After only a small amount of pain messing about with MinGW, I managed to get the code compiled nicely into a DLL. At this point, I am of course perfectly able just to use the P/Invoke capabilities of .NET and do some hackery to integrate the ARPACK stuff with my existing code and dnAnalytics. Yet, I am also inclined to do this whole task properly and basically write a managed wrapper for ARPACK that is tightly conforms with dnAnalytics. I could then perhaps submit these wrapper types (along with a few unit tests?) as a repository patch to the dnAnalytics team in the hope that they&#8217;ll take it and add it to the next release. As with most other projects at this time, I will have to see what time permits me, though I would certainly hope to contribute something substantial to what truly is a terrific project that I would love to see expand further.</p>
<br />Posted in Personal, Programming, Projects, Software Tagged: .net, algorithms, arnoldi, arnoldi algorithm, arpack, c#, code libraries, dense matrix, diagonalisation, dnanalytics, documentation, eigendecomposition, eigenvalues, eigenvectors, f#, fortran, fortran77, intel math kernel library, intel mkl, lanczos, lanczos algorithm, libraries, linear algebra, matlab, matrices, matrix, matrix decomposition, mersenne twister, numerical algorithms, numerical analysis, open-source, pseudo-random, pseudorandom, random number generator, rng, sparse matrix, spectral theory, stackoverflow, statistical functions, statistics, vectors <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/alexreg.wordpress.com/185/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/alexreg.wordpress.com/185/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/alexreg.wordpress.com/185/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/alexreg.wordpress.com/185/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/alexreg.wordpress.com/185/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/alexreg.wordpress.com/185/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/alexreg.wordpress.com/185/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/alexreg.wordpress.com/185/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/alexreg.wordpress.com/185/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/alexreg.wordpress.com/185/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/alexreg.wordpress.com/185/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/alexreg.wordpress.com/185/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/alexreg.wordpress.com/185/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/alexreg.wordpress.com/185/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=alexreg.wordpress.com&amp;blog=3367172&amp;post=185&amp;subd=alexreg&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://alexreg.wordpress.com/2009/05/15/numerical-analysis-for-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eed60bdfc964ec62cc48aa6020a03d7b?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=PG" medium="image">
			<media:title type="html">Noldorin</media:title>
		</media:content>
	</item>
		<item>
		<title>LINQ to YAML</title>
		<link>http://alexreg.wordpress.com/2009/05/14/linq-to-yaml/</link>
		<comments>http://alexreg.wordpress.com/2009/05/14/linq-to-yaml/#comments</comments>
		<pubDate>Wed, 13 May 2009 23:53:48 +0000</pubDate>
		<dc:creator>Noldorin</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[.net 3.5]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[c# 3.0]]></category>
		<category><![CDATA[data format]]></category>
		<category><![CDATA[ienumerable]]></category>
		<category><![CDATA[lambda expressions]]></category>
		<category><![CDATA[linq]]></category>
		<category><![CDATA[linq to objects]]></category>
		<category><![CDATA[linq to yaml]]></category>
		<category><![CDATA[markup language]]></category>
		<category><![CDATA[serialisation]]></category>
		<category><![CDATA[serialization]]></category>
		<category><![CDATA[vb.net]]></category>
		<category><![CDATA[xml dom]]></category>
		<category><![CDATA[yaml]]></category>

		<guid isPermaLink="false">http://alexreg.wordpress.com/?p=171</guid>
		<description><![CDATA[LINQ to XML is one of the many technologies introduced with the .NET Framework 3.5, and one that is certainly a step forward in terms of usability. It allows querying in both the functional style (using LINQ and lambda expressions) and the more traditional imperative one, meaning that it&#8217;s a great tool for concisely working [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=alexreg.wordpress.com&amp;blog=3367172&amp;post=171&amp;subd=alexreg&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://msdn.microsoft.com/en-us/library/bb387098.aspx">LINQ to XML</a> is one of the many technologies introduced with the .NET Framework 3.5, and one that is certainly a step forward in terms of usability. It allows querying in both the functional style (using LINQ and lambda expressions) and the more traditional imperative one, meaning that it&#8217;s a great tool for concisely working with XML data in any sort of application, and undoubtedly a significant improvement over the old XML DOM that resides in the <em>System.Xml</em> namespace.</p>
<p>In the spirit of LINQ, and with the advent of <a href="http://www.yaml.org/">YAML</a>, I recntly decided it was about time that this new &#8220;markup language&#8221; were integrated with LINQ. Surprisingly, there does not already exist anything akin to LINQ to YAML out there (though there are a couple of fairly usable implementations of a YAML reader/writer for .NET). This seemed to me like a good chance to potentially create something that might be used by more than the odd .NET developer or two. My plans are to implement a LINQ to YAML provider either from scratch or on top of one of the existing YAML libraries. (Which option I choose will depend on the state of the existing projects, which I haven&#8217;t yet investigated properly. I am however suspecting that it might be worthwhile writing my own, since it would a) teach me all the intricacies of YAML, and b) allow me to support the latest version [1.2], which the existing libraries do not.)</p>
<p>Before I launch into an overview of my intended implementation, here is a little bit about YAML itself, for those who aren&#8217;t already familiar with it. Although technically YAML isn&#8217;t a markup language (after all, the recursive acronym stands for <em>YAML Ain&#8217;t Markup Language</em>) &#8211; it is rather a serialisation format &#8211; it does essentially fulfill the the role that XML  traditionally has, in a variety of common situations. I&#8217;m not going to try to sell the format to you right now, but it should suffice to say that you wouldn&#8217;t have reached this far in the post if you weren&#8217;t already at least intrigued! Without doubt, the format is actively gaining popularity because of it&#8217;s ultra-lightweight syntax and suitability for hand editing, perhaps the two points that summarise its advantages over XML.</p>
<p>Anyway, here&#8217;s a short example of a YAML document (taken straight from <a href="http://en.wikipedia.org/wiki/Yaml#Sample_document">the Wikipedia page</a>), so you can see precisely how pleasant it is to work with (at least for humans).</p>
<p>&#8212;</p>
<pre>receipt:     Oz-Ware Purchase Invoice
date:        2007-08-06
customer:
    given:   Dorothy
    family:  Gale

items:
    - part_no:   A4786
      descrip:   Water Bucket (Filled)
      price:     1.47
      quantity:  4

    - part_no:   E1628
      descrip:   High Heeled "Ruby" Slippers
      price:     100.27
      quantity:  1

bill-to:  &amp;id001
    street: |
            123 Tornado Alley
            Suite 16
    city:   East Westville
    state:  KS

ship-to:  *id001

specialDelivery:  &gt;
    Follow the Yellow Brick
    Road to the Emerald City.
    Pay no attention to the
    man behind the curtain.
...</pre>
<p>Of course, the great thing about YAML, which is demonstrated clearly by this example, is that you don&#8217;t have to have any real knowledge about YAML to understand exactly and immediately what the data represents, and as a bonus it doesn&#8217;t hurt your eyes to stare at for too long! Even the referencing syntax should be fairly self evident. (<em>&amp;id00</em> and<em> *id001</em> would surely be nothing new to C programmers.)</p>
<p>The semantics as well as the syntax of YAML obviously differ to those of XML greatly, although there is almost always some sort of correspondence between the features and possibilities that the two formats offer. The only notable missing feature when contrasted to XML is attributes, yet their usefulness is questionable anyway.</p>
<p>Right, so now I ought to explain a bit about how I actually plan to design this library. The basic framework will be virtually equivalent to that of LINQ to XML. In other words, the hierarchy will be largely based around an abstract <em>YamlObject</em> (<em>YObject</em>?) class, and will look very much like the one contained within <em>System.Xml.Linq</em>.</p>
<p><a href="http://i.msdn.microsoft.com/Bb308960.xlinqoverview01(en-us,MSDN.10).jpg"><img style="width:100%;" src="http://i.msdn.microsoft.com/Bb308960.xlinqoverview01(en-us,MSDN.10).jpg" alt="Diagram of LINQ to XML class hierarchy" /></a><em>LINQ to XML class hierarchy</em></p>
<p>Though LINQ to YAML must of course accomodate for the unique nature of the format, I would initially aim for minimal difference and only significantly adjust the hierarchy when it is found to be necessary. Classes such as <em>XCData</em> and <em>XDocumentType</em> would not apply at all to YAML, yet there would need to be a place for a <em>YReference</em> or such somewhere in the hierarchy. The referencing aspect of YAML will likely prove to be one of the more interesting challenges; while YAML&#8217;s lists, maps (dictionaries), and combinations thereof would seem relatively straightforward with regards to emulation of the LINQ to XML design, references would introduce a substantially novel concept. Some sort of implementation of lazy evaluation followed by concrete referencing should be able to solve the problem, but there&#8217;s no way to predict how well this might work in practice at this moment.</p>
<p>What I realised only after deciding to create a LINQ to YAML library is that among LINQ providers, LINQ to XML is somewhat special in that the LINQ aspect of it is built <em>on top of</em> <a href="http://msdn.microsoft.com/en-us/library/bb397919.aspx">LINQ to Objects</a> (i.e. LINQ using <em>IEnumerable&lt;T&gt;</em> objects), with only a relatively small number of extension methods specific to LINQ to XML. Indeed, most LINQ providers (LINQ to Objects and LINQ to SQL among others) require you to implement the <em>IQueryable</em> and <em>IQueryProvider</em> interfaces to provide complex logic for interpreting and returning the results of expressions, as well as evaluating complex expression trees.  All this means that I can pretty much just design a DOM  to a certain style (i.e. one suited to functional code, like LINQ to XML), and let LINQ to Objects to everything else for me.</p>
<p>As I can&#8217;t think of anything more worth mentioning about my project at this time, I shall leave any more specific and complex details to a future post. Still, do by all means feel free to query me about my plans &#8211; I would be glad to answer any questions, and even gladder to receive some suggestions as how you think I might design LINQ to YAML, or simply a nod that you might find this useful at some point. I don&#8217;t anticipate this project to be a very long one, though I must say that both my work and free-time schedule are likely to be fairly messed up for the next month or two, therefore I&#8217;m not going to promise when I&#8217;ll get around to my initial release. Whenever it so happens, I will duly post the link to the project page on Launchpad (or wherever I decide to host it).</p>
<br />Posted in Programming, Projects, Software Tagged: .net, .net 3.5, c#, c# 3.0, data format, ienumerable, lambda expressions, linq, linq to objects, linq to yaml, markup language, serialisation, serialization, vb.net, xml dom, yaml <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/alexreg.wordpress.com/171/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/alexreg.wordpress.com/171/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/alexreg.wordpress.com/171/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/alexreg.wordpress.com/171/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/alexreg.wordpress.com/171/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/alexreg.wordpress.com/171/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/alexreg.wordpress.com/171/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/alexreg.wordpress.com/171/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/alexreg.wordpress.com/171/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/alexreg.wordpress.com/171/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/alexreg.wordpress.com/171/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/alexreg.wordpress.com/171/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/alexreg.wordpress.com/171/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/alexreg.wordpress.com/171/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=alexreg.wordpress.com&amp;blog=3367172&amp;post=171&amp;subd=alexreg&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://alexreg.wordpress.com/2009/05/14/linq-to-yaml/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eed60bdfc964ec62cc48aa6020a03d7b?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=PG" medium="image">
			<media:title type="html">Noldorin</media:title>
		</media:content>

		<media:content url="http://i.msdn.microsoft.com/Bb308960.xlinqoverview01(en-us,MSDN.10).jpg" medium="image">
			<media:title type="html">Diagram of LINQ to XML class hierarchy</media:title>
		</media:content>
	</item>
		<item>
		<title>The Optimality of Morals</title>
		<link>http://alexreg.wordpress.com/2009/05/04/the-optimality-of-morals/</link>
		<comments>http://alexreg.wordpress.com/2009/05/04/the-optimality-of-morals/#comments</comments>
		<pubDate>Sun, 03 May 2009 23:29:45 +0000</pubDate>
		<dc:creator>Noldorin</dc:creator>
				<category><![CDATA[Philosophy]]></category>
		<category><![CDATA[altruism]]></category>
		<category><![CDATA[analytic ethics]]></category>
		<category><![CDATA[creationism]]></category>
		<category><![CDATA[egoism]]></category>
		<category><![CDATA[ethics]]></category>
		<category><![CDATA[evolution]]></category>
		<category><![CDATA[hypothesis]]></category>
		<category><![CDATA[immanuel kant]]></category>
		<category><![CDATA[john stuart mill]]></category>
		<category><![CDATA[kant]]></category>
		<category><![CDATA[meaning of life]]></category>
		<category><![CDATA[meta-ethics]]></category>
		<category><![CDATA[morality]]></category>
		<category><![CDATA[morals]]></category>
		<category><![CDATA[optimality]]></category>
		<category><![CDATA[philosophical theory]]></category>
		<category><![CDATA[selfishness]]></category>
		<category><![CDATA[spinoza's god]]></category>
		<category><![CDATA[theory]]></category>
		<category><![CDATA[utilitarianism]]></category>

		<guid isPermaLink="false">http://alexreg.wordpress.com/?p=137</guid>
		<description><![CDATA[This post essentially follows on from the Notes on Kant post by David, which having prompted rather a lot of comments and one or two conversations, led to a few interesting conclusions on the subject of morality. Here, however, I mainly intend to express my own views and conclusions on the nature of morals (though [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=alexreg.wordpress.com&amp;blog=3367172&amp;post=137&amp;subd=alexreg&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong></strong></p>
<p>This post essentially follows on from the <a href="http://alsuren.wordpress.com/2009/04/04/notes-on-kant/">Notes on Kant</a> post by David, which having prompted rather a lot of comments and one or two conversations, led to a few interesting conclusions on the subject of morality. Here, however, I mainly intend to express my own views and conclusions on the nature of morals (though David seems to be of much accordance, at least in his end point). I&#8217;ll leave it to anyone who wishes to comment to counter my points.</p>
<p>To start, I should mention that my own philosophy on morals seems to be largely in accordance with rule <a href="http://en.wikipedia.org/wiki/Utilitarianism">utilitarianism</a> (or at a minor variant of it). What follows is pretty much the set of ideas that guided me to the eventual conclusion regarding optimality. Specifically, I argue that an action is moral if it is beneficial to either oneself or society (or both) and <em>not</em> detrimental to the well-being and continuation of the society as a whole. The intentions of the individual performing the action must also satisfy these conditions if the action is to be deemed moral, else the action must be morally neutral at best. Importantly, this specification implies that choices made with self-interest in mind can be moral so long as the communal benefit is non-negative. This becomes quite obvious given the assumption that the well-being of individuals in general contributes to the well-being of society (at least in an indirect way). Note that the arbiter in all these cases must be hypothetical as well as purely objective (nature itself, if you will), meaning that even though a certain action may be considered immoral as a consensus of society, it may nevertheless be neutral or even moral in actuality. Saying this, in a well-functioning and successful society, there would seem to be a general requirement that the judgement of moral worth of actions is reasonably accurate in a high proportion of situations.</p>
<p>Considering these points and their commonalities is primarily what led me to believe that when you boil everything down, morals are nothing but an approximation to optimality of society. Now as soon one mentions optimality, the question of a measure automaticfally follows. Of course, most people probably have some vague notion of what an &#8220;optimal society&#8221; is, but since the aim here is to be as formal and specific as possible, I really need to define a <a href="http://en.wikipedia.org/wiki/Cost_function">cost function</a>, at least in loose terms. At this point, I would imagine that the opinions of most people would tend to diverge rapidly. Some would reason that the cost function is purely dependant on well-being/happiness/pleasure (whether more for the individual or society separates the hedonists from the utilitarians), while others would state the straightforward biological (yet to many cold and unpleasing) view that optimality is but a measure of the size of the population and thus the continued ability to self-replicate. Finally, the more religious among us might contend that optimality is simply the perfectly obedient following of teachings passed down to us by God. In essence, this cost function is nothing other than the &#8220;<a href="http://en.wikipedia.org/wiki/Meaning_of_life">meaning of life</a>&#8221; (in the widest possible sense) &#8211; something that may never be defined, and certainly not a discussion I&#8217;m going to include in this post! Whatever view people wish to take, I believe that the basic statement that &#8220;morals are an approximation for optimality&#8221; holds well in all cases. Like the nature of this optimality, the mechanism by which the concept of morality has been instilled in us (evolution, creationism, <a href="http://plato.stanford.edu/entries/spinoza/#GodNat">Spinoza&#8217;s God</a>, or whatever) is also open to debate, but nonetheless is not able invalidate this theory in itself, at least in the way I see it. Yet all these concepts of optimality surely do have similarities. Another important feature of the cost function is that parameters should be not only the current state of humanity and the world, but also the states at points in the future (perhaps stretching infinitely far ahead in time). In the end, I think I can say that I do personally feel reasonably content with this definition of morals (albeit most likely an incomplete one). In my mind one cannot proceed any further in a formal definition without invoking reasons akin to the &#8220;meaning of life&#8221; such as those just mentioned &#8211; all very contentious or speculative and therefore not terribly helpful as bases for any fundamental theories, in my view.</p>
<div>Now to properly round off these theories, I ought to explain in more detail what I mean by an &#8220;approximation&#8221; to optimality. In my conclusion, I came to realise that moral principles (stressing the fact these principles are what are percdeived by men to be moral) may <em>not necessarily</em> lead to optimality in all cases, however you want to define the term. There can clearly exist an action performed at a certain time that to the best of everyone&#8217;s knowledge appears moral, yet has long-term ramifications that are generally negative &#8211; an unlikely case perhaps, but a quite possible one irrespective. It then follows that either a) the action cannot actually be considered absolutely moral because of these consequences in the (distant) future, or b) the motivation/action is perfectly moral (given the limitations in the nature of the actor) but not necessarily <em>optimal</em> under whatever cost function you choose. I would think option a) would appear immediately  quite wrong, since it would contradict the idea that moral actions can be knowingly performed, which just silliness under any definition. We are then forced to accept option b), in other words that morals are only approximation guides to optimal behaviour and therefore optimal results (though most likely very good approximations). The next question is: does there exist any <em>better</em> approximation to optimality than morality? Of course, omniscience combined with perfect reasoning might be considered the ideal way to produce an optimal society and would seem to appear more &#8220;useful&#8221; than morals, but this is something which we as humans fall short of by an effectively infinite margin. Let&#8217;s suppose the evolutionary viewpoint for a moment here, simply because it leads to a curious hypothetical case. Is there a point at which we as a species may become intelligent enough to produce a more optimal society purely by reasoning? Is there a threshold at which it suddenly becomes more sensible to follow pure reason than moral instincts, or will both always be required to varying degrees? I&#8217;ll leave those questions unanswered, since they are largely side points to my cse, though it does at least highlight the issue in relation to current and past socities. Now surely no-one would argue that high-level reasoning can&#8217;t be used alongside (augmenting?) instinctual/inherent morals (indeed it is arguably a more &#8220;intelligent&#8221; form of morals that makes mankind particularly moral). Nevertheless it should be quite clear in looking around ourselves that there are dangers in the outcomes of limited reasoning overriding recognisably moral behaviour. Perhaps we can even attribute immoral behaviour at its root to to the arrogance or <a href="http://en.wikipedia.org/wiki/Selfishness">egotism</a> (by this I really mean selfishness) of humans &#8211; whether in valuing their own well-being over that of society as a whole or their own powers of reasoning over moral principles. The latter is perhaps a more unintentional form, due to the failure of limited consciousness to realise its own limitations in forseeing complex (or at times even relatively simple) consequences of actions. To explain what might appear to be the widespread existance of the dominance of egotism in individuals&#8217; personal cost functions, we may attribute this to the imperfection of our nature or the fact that evolution has taken an imperfect shortcut. In either case, it is certain that placing a significant weight on self-interest is highly beneficial to both the individual and the society, yet just a bit too much can have hugely negative effects. For me, what the commonness of egotism implies is nothing but the presence of something other than morality in people&#8217;s own cost functions &#8211; whereas morality has its benefits and imperfections, egotism simply has less of the former and more of the latter, and is grouped outside of morality for this reason (while a modicum of self-interest being on the moral side). Clearly, there is some sort of spectrum in judging the moral value of traits. Drawing all the previously mentioned things together, I feel I can now justify my definition of morality as an &#8220;approximation&#8221; or &#8220;shortcut&#8221; to optimal behaviour for the species as a whole.</div>
<p>It is without doubt important to stress that morals have their own imperfections and limitations, like analytical reasoning, and depend on the individuals (or society thereof) in which they have formed. Yet depending on how you look at it, morals have  evolved or been designed specifically for the purpose of optimal society. Although morality may be less adaptable than intelligence (at least over the timespans ranging from days to maybe lifetimes), it assuredly has a more &#8220;tailored&#8221; purpose, and therefore has its place alongside, and arguably ahead of, analytical reasoning.</p>
<p>If I were to now summarise how I believe optimal behaviour should be guided, I would say that it&#8217;s necessary to be somewhat careful not to propose something too uncomprimisable. In reality, it&#8217;s almost always the case that reasons are more intricate and subtle than immediately apparent. In stating an emphasis on paying due attention to intrinsic morals (loosely, which can be recognised as principles and codes that typically &#8220;feel right&#8221; and are &#8220;seen to be right&#8221; by concensus of society), and contrarily wariness in ignoring these morals in favour of some sort of pure reasoning. &#8220;Reasoning&#8221;, after all, when performed by humans, cannot help but be intruded by egotistical motives, among other notable imperfections. Do we not after all have a fear of so-called purely &#8220;rational&#8221; or &#8220;logical&#8221; machines not hesitating to perform tasks that are undeniably immoral in the eyes of man (if not only founded in science fiction and our imaginations)?</p>
<p>As a quick final note, I ought to mention that nowhere in my musings have I required morals to be static in nature. Equally, there would not seem to be any issue with them being unchangeable. At this point I&#8217;m further tempted to divide morals into two categories: intrinsic and social. Again, this is a matter on which I&#8217;m only going to lightly touch. The latter is the one of particular interest in that it could imply a varying cost function for optimality. It also suggests a mutual feedback cycle between the will of society and contemporary moral values (with analytical reasoning somewhere in the process, potentially acting both positively or negatively).</p>
<p>Right, so this post has wound on long enough by now, and is only getting increasingly vague and leaving more loose ends. Still, I hope that I&#8217;ve at least partially conveyed my theories and general impressions on the subject. I&#8217;m not sure how everything appears to others who haven&#8217;t followed the continuous discussion on the wider topic (largely originating with David&#8217;s post). I&#8217;d certainly be keen to hear what anyone else thinks on the subject and the ideas presented here. I would not at all be surprised to receive opinions that this relation of morals to optimailty seems distasteful or even incomplete to many people. Indeed, I am not sure that I am wholly satisfied with this explanation as the &#8220;root&#8221; of morals. (How can I, having already cynically accepted the fallibility of human rationalisation?) Maybe it is as a student of physics that I realise our theories of the nature, physical or human, are always but approximations to a more profound reality.</p>
<br />Posted in Philosophy Tagged: altruism, analytic ethics, creationism, egoism, ethics, evolution, hypothesis, immanuel kant, john stuart mill, kant, meaning of life, meta-ethics, morality, morals, optimality, philosophical theory, Philosophy, selfishness, spinoza's god, theory, utilitarianism <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/alexreg.wordpress.com/137/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/alexreg.wordpress.com/137/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/alexreg.wordpress.com/137/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/alexreg.wordpress.com/137/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/alexreg.wordpress.com/137/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/alexreg.wordpress.com/137/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/alexreg.wordpress.com/137/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/alexreg.wordpress.com/137/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/alexreg.wordpress.com/137/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/alexreg.wordpress.com/137/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/alexreg.wordpress.com/137/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/alexreg.wordpress.com/137/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/alexreg.wordpress.com/137/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/alexreg.wordpress.com/137/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=alexreg.wordpress.com&amp;blog=3367172&amp;post=137&amp;subd=alexreg&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://alexreg.wordpress.com/2009/05/04/the-optimality-of-morals/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eed60bdfc964ec62cc48aa6020a03d7b?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=PG" medium="image">
			<media:title type="html">Noldorin</media:title>
		</media:content>
	</item>
		<item>
		<title>Strongly-Typed CSV Reader in C#</title>
		<link>http://alexreg.wordpress.com/2009/05/03/strongly-typed-csv-reader-in-c/</link>
		<comments>http://alexreg.wordpress.com/2009/05/03/strongly-typed-csv-reader-in-c/#comments</comments>
		<pubDate>Sun, 03 May 2009 13:41:28 +0000</pubDate>
		<dc:creator>Noldorin</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[.net 3.5]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[c# 3.0]]></category>
		<category><![CDATA[comma separated values]]></category>
		<category><![CDATA[csv]]></category>
		<category><![CDATA[file i/o]]></category>
		<category><![CDATA[generics]]></category>
		<category><![CDATA[linq]]></category>
		<category><![CDATA[object initializers]]></category>
		<category><![CDATA[reflection]]></category>
		<category><![CDATA[streamreader]]></category>
		<category><![CDATA[strongly-typed]]></category>

		<guid isPermaLink="false">http://alexreg.wordpress.com/?p=142</guid>
		<description><![CDATA[As part of a project on which I&#8217;ve recently started working, I found it necessary to write a class that reads entries from CSV files. Such a simple format, you might think, so why would I bother sharing such trivial code? Indeed, it is a relatively short class, but I thought I&#8217;d post it here [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=alexreg.wordpress.com&amp;blog=3367172&amp;post=142&amp;subd=alexreg&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>As part of a project on which I&#8217;ve recently started working, I found it necessary to write a class that reads entries from <a href="http://en.wikipedia.org/wiki/Comma-separated_values">CSV</a> files. Such a simple format, you might think, so why would I bother sharing such trivial code? Indeed, it is a relatively short class, but I thought I&#8217;d post it here nonetheless, primarily because I believe its usage promotes a design practice of which I am particularly fond, and I suspect (hope) other people may appreciate as well. There are also a few bits of code that might be considered interesting (and unusual) from a language/design perspective.</p>
<p>When I decided to formalise the logic for reading from CSV files, I firstly thought it would be nice to write something in the spirit of .NET 3.5 &#8211; in this case, easily compatible with LINQ, fully generic (strongly-typed), and attribute-oriented (as seems to be the trend in APIs nowadays). Before I launch into any further discussion, here&#8217;s the code for the class in full.</p>
<pre class="csharp" style="border:1px solid #d0d0d0;overflow:auto;font-family:monospace;color:#000066;background-color:#f0f0f0;width:100%;max-height:40em;margin-bottom:1em;"><span style="color:#0600FF;">using</span> <span style="color:#008080;">System</span><span style="color:#008000;">;</span>
<span style="color:#0600FF;">using</span> <span style="color:#008080;">System.ComponentModel</span><span style="color:#008000;">;</span>
<span style="color:#0600FF;">using</span> <span style="color:#008080;">System.Collections.Generic</span><span style="color:#008000;">;</span>
<span style="color:#0600FF;">using</span> <span style="color:#008080;">System.IO</span><span style="color:#008000;">;</span>
<span style="color:#0600FF;">using</span> <span style="color:#008080;">System.Linq</span><span style="color:#008000;">;</span>
<span style="color:#0600FF;">using</span> <span style="color:#008080;">System.Reflection</span><span style="color:#008000;">;</span>
<span style="color:#0600FF;">using</span> <span style="color:#008080;">System.Text</span><span style="color:#008000;">;</span>

<span style="color:#0600FF;">namespace</span> NetworkAnalyser
<span style="color:#000000;">{</span>
    <span style="color:#0600FF;">public</span> <span style="color:#FF0000;">class</span> CsvReader<span style="color:#008000;">&lt;</span>TEntry<span style="color:#008000;">&gt;</span> <span style="color:#008000;">:</span> IDisposable where TEntry <span style="color:#008000;">:</span> <span style="color:#FF0000;">struct</span>
    <span style="color:#000000;">{</span>
        <span style="color:#0600FF;">private</span> StreamReader streamReader<span style="color:#008000;">;</span>
        <span style="color:#0600FF;">private</span> FieldTypeInfo<span style="color:#000000;">[</span><span style="color:#000000;">]</span> fieldTypeInfos<span style="color:#008000;">;</span>

        <span style="color:#0600FF;">private</span> <span style="color:#FF0000;">bool</span> isDisposed <span style="color:#008000;">=</span> false<span style="color:#008000;">;</span>

        <span style="color:#0600FF;">public</span> CsvReader<span style="color:#000000;">(</span><span style="color:#FF0000;">string</span> path<span style="color:#000000;">)</span>
        <span style="color:#000000;">{</span>
            streamReader <span style="color:#008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color:#008000;">new</span></a> StreamReader<span style="color:#000000;">(</span>path<span style="color:#000000;">)</span><span style="color:#008000;">;</span>
            Initialize<span style="color:#000000;">(</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
        <span style="color:#000000;">}</span>

        <span style="color:#0600FF;">public</span> CsvReader<span style="color:#000000;">(</span>Stream stream<span style="color:#000000;">)</span>
        <span style="color:#000000;">{</span>
            streamReader <span style="color:#008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color:#008000;">new</span></a> StreamReader<span style="color:#000000;">(</span>stream<span style="color:#000000;">)</span><span style="color:#008000;">;</span>
            Initialize<span style="color:#000000;">(</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
        <span style="color:#000000;">}</span>

        ~CsvReader<span style="color:#000000;">(</span><span style="color:#000000;">)</span>
        <span style="color:#000000;">{</span>
            Dispose<span style="color:#000000;">(</span><span style="color:#0600FF;">false</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
        <span style="color:#000000;">}</span>

        <span style="color:#0600FF;">public</span> <span style="color:#0600FF;">void</span> Dispose<span style="color:#000000;">(</span><span style="color:#000000;">)</span>
        <span style="color:#000000;">{</span>
            Dispose<span style="color:#000000;">(</span><span style="color:#0600FF;">true</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
            GC.<span style="color:#0000FF;">SuppressFinalize</span><span style="color:#000000;">(</span><span style="color:#0600FF;">this</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
        <span style="color:#000000;">}</span>

        <span style="color:#0600FF;">protected</span> <span style="color:#0600FF;">virtual</span> <span style="color:#0600FF;">void</span> Dispose<span style="color:#000000;">(</span><span style="color:#FF0000;">bool</span> disposing<span style="color:#000000;">)</span>
        <span style="color:#000000;">{</span>
            <span style="color:#0600FF;">if</span> <span style="color:#000000;">(</span><span style="color:#008000;">!</span>isDisposed<span style="color:#000000;">)</span>
            <span style="color:#000000;">{</span>
                <span style="color:#0600FF;">if</span> <span style="color:#000000;">(</span>disposing<span style="color:#000000;">)</span>
                <span style="color:#000000;">{</span>
                    <span style="color:#0600FF;">if</span> <span style="color:#000000;">(</span>streamReader <span style="color:#008000;">!=</span> <span style="color:#0600FF;">null</span><span style="color:#000000;">)</span>
                        streamReader.<span style="color:#0000FF;">Dispose</span><span style="color:#000000;">(</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
                <span style="color:#000000;">}</span>
            <span style="color:#000000;">}</span>

            isDisposed <span style="color:#008000;">=</span> true<span style="color:#008000;">;</span>
        <span style="color:#000000;">}</span>

        <span style="color:#0600FF;">public</span> IEnumerable<span style="color:#008000;">&lt;</span>TEntry<span style="color:#008000;">&gt;</span> ReadAllEntries<span style="color:#000000;">(</span><span style="color:#000000;">)</span>
        <span style="color:#000000;">{</span>
            TEntry<span style="color:#008000;">?</span> entry<span style="color:#008000;">;</span>
            <span style="color:#0600FF;">while</span> <span style="color:#000000;">(</span><span style="color:#000000;">(</span>entry <span style="color:#008000;">=</span> ReadEntry<span style="color:#000000;">(</span><span style="color:#000000;">)</span><span style="color:#000000;">)</span>.<span style="color:#0000FF;">HasValue</span><span style="color:#000000;">)</span>
                yield <span style="color:#0600FF;">return</span> entry.<span style="color:#0000FF;">Value</span><span style="color:#008000;">;</span>
        <span style="color:#000000;">}</span>

        <span style="color:#0600FF;">public</span> TEntry<span style="color:#008000;">?</span> ReadEntry<span style="color:#000000;">(</span><span style="color:#000000;">)</span>
        <span style="color:#000000;">{</span>
            var line <span style="color:#008000;">=</span> streamReader.<span style="color:#0000FF;">ReadLine</span><span style="color:#000000;">(</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
            <span style="color:#0600FF;">if</span> <span style="color:#000000;">(</span>line <span style="color:#008000;">==</span> <span style="color:#0600FF;">null</span><span style="color:#000000;">)</span>
                <span style="color:#0600FF;">return</span> null<span style="color:#008000;">;</span>

            var entry <span style="color:#008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color:#008000;">new</span></a> TEntry<span style="color:#000000;">(</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
            var fields <span style="color:#008000;">=</span> line.<span style="color:#0000FF;">Split</span><span style="color:#000000;">(</span><a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color:#008000;">new</span></a> <span style="color:#FF0000;">char</span><span style="color:#000000;">[</span><span style="color:#000000;">]</span> <span style="color:#000000;">{</span> <span style="color:#666666;">','</span> <span style="color:#000000;">}</span>, StringSplitOptions.<span style="color:#0000FF;">None</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
            FieldTypeInfo fieldTypeInfo<span style="color:#008000;">;</span>
            <span style="color:#FF0000;">object</span> fieldValue<span style="color:#008000;">;</span>

            <span style="color:#0600FF;">for</span> <span style="color:#000000;">(</span><span style="color:#FF0000;">int</span> i <span style="color:#008000;">=</span> <span style="color:#FF0000;">0</span><span style="color:#008000;">;</span> i <span style="color:#008000;">&lt;</span> fields.<span style="color:#0000FF;">Length</span><span style="color:#008000;">;</span> i<span style="color:#008000;">++</span><span style="color:#000000;">)</span>
            <span style="color:#000000;">{</span>
                fieldTypeInfo <span style="color:#008000;">=</span> fieldTypeInfos<span style="color:#000000;">[</span>i<span style="color:#000000;">]</span><span style="color:#008000;">;</span>
                fieldValue <span style="color:#008000;">=</span> fieldTypeInfo.<span style="color:#0000FF;">TypeConverter</span>.<span style="color:#0000FF;">ConvertFromString</span><span style="color:#000000;">(</span>fields<span style="color:#000000;">[</span>i<span style="color:#000000;">]</span>.<span style="color:#0000FF;">Trim</span><span style="color:#000000;">(</span><span style="color:#000000;">)</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
                fieldTypeInfo.<span style="color:#0000FF;">FieldInfo</span>.<span style="color:#0000FF;">SetValueDirect</span><span style="color:#000000;">(</span>__makeref<span style="color:#000000;">(</span>entry<span style="color:#000000;">)</span>, fieldValue<span style="color:#000000;">)</span><span style="color:#008000;">;</span>
            <span style="color:#000000;">}</span>

            <span style="color:#0600FF;">return</span> entry<span style="color:#008000;">;</span>
        <span style="color:#000000;">}</span>

        <span style="color:#0600FF;">private</span> <span style="color:#0600FF;">void</span> Initialize<span style="color:#000000;">(</span><span style="color:#000000;">)</span>
        <span style="color:#000000;">{</span>
            var entryType <span style="color:#008000;">=</span> <a href="http://www.google.com/search?q=typeof+msdn.microsoft.com"><span style="color:#008000;">typeof</span></a><span style="color:#000000;">(</span>TEntry<span style="color:#000000;">)</span><span style="color:#008000;">;</span>
            fieldTypeInfos <span style="color:#008000;">=</span> <span style="color:#000000;">(</span>from fieldInfo <span style="color:#0600FF;">in</span> entryType.<span style="color:#0000FF;">GetFields</span><span style="color:#000000;">(</span>BindingFlags.<span style="color:#0000FF;">Instance</span> <span style="color:#008000;">|</span>
                                  BindingFlags.<span style="color:#0600FF;">Public</span><span style="color:#000000;">)</span>
                              let fieldTypeConverterAttrib <span style="color:#008000;">=</span> fieldInfo.<span style="color:#0000FF;">GetCustomAttributes</span><span style="color:#000000;">(</span>
                                  <a href="http://www.google.com/search?q=typeof+msdn.microsoft.com"><span style="color:#008000;">typeof</span></a><span style="color:#000000;">(</span>TypeConverterAttribute<span style="color:#000000;">)</span>, <span style="color:#0600FF;">true</span><span style="color:#000000;">)</span>.<span style="color:#0000FF;">SingleOrDefault</span><span style="color:#000000;">(</span><span style="color:#000000;">)</span>
                                  <span style="color:#0600FF;">as</span> TypeConverterAttribute
                              let fieldTypeConverter <span style="color:#008000;">=</span> <span style="color:#000000;">(</span>fieldTypeConverterAttrib <span style="color:#008000;">==</span> <span style="color:#0600FF;">null</span><span style="color:#000000;">)</span> <span style="color:#008000;">?</span> <span style="color:#0600FF;">null</span> <span style="color:#008000;">:</span>
                                  Activator.<span style="color:#0000FF;">CreateInstance</span><span style="color:#000000;">(</span>Type.<span style="color:#0000FF;">GetType</span><span style="color:#000000;">(</span>
                                      fieldTypeConverterAttrib.<span style="color:#0000FF;">ConverterTypeName</span><span style="color:#000000;">)</span><span style="color:#000000;">)</span>
                                  <span style="color:#0600FF;">as</span> TypeConverter
                              select <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color:#008000;">new</span></a> FieldTypeInfo<span style="color:#000000;">(</span><span style="color:#000000;">)</span>
                              <span style="color:#000000;">{</span>
                                  FieldInfo <span style="color:#008000;">=</span> fieldInfo,
                                  TypeConverter <span style="color:#008000;">=</span> fieldTypeConverter <span style="color:#008000;">??</span>
                                      TypeDescriptor.<span style="color:#0000FF;">GetConverter</span><span style="color:#000000;">(</span>fieldInfo.<span style="color:#0000FF;">FieldType</span><span style="color:#000000;">)</span>
                              <span style="color:#000000;">}</span><span style="color:#000000;">)</span>.<span style="color:#0000FF;">ToArray</span><span style="color:#000000;">(</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
        <span style="color:#000000;">}</span>

        <span style="color:#0600FF;">private</span> <span style="color:#FF0000;">struct</span> FieldTypeInfo
        <span style="color:#000000;">{</span>
            <span style="color:#0600FF;">public</span> FieldInfo FieldInfo<span style="color:#008000;">;</span>
            <span style="color:#0600FF;">public</span> TypeConverter TypeConverter<span style="color:#008000;">;</span>
        <span style="color:#000000;">}</span>
    <span style="color:#000000;">}</span>
<span style="color:#000000;">}</span></pre>
<p>(Please excuse the utter lack of comments in the code. Most of it is self-explanatory, but admittedly some parts are probably not. I put it together pretty quickly, but I may get around to commenting it some time soon. Some basic error handling might also be nice.)</p>
<p>At this point it may seem rather excessive just to read data from a CSV file, but I hope you&#8217;ll agree that it&#8217;s worthwhile once you see an example of typical usage.</p>
<p>The first step is to define a structure (<em>struct</em>) that holds each entry in memory. Here we&#8217;re going to define one that holds some basic information about a programming language.</p>
<pre class="csharp" style="border:1px solid #d0d0d0;overflow:auto;font-family:monospace;color:#000066;background-color:#f0f0f0;width:100%;margin-bottom:1em;"><span style="color:#0600FF;">public</span> <span style="color:#FF0000;">struct</span> LanguageEntry
<span style="color:#000000;">{</span>
    <span style="color:#0600FF;">public</span> <span style="color:#FF0000;">string</span> Name<span style="color:#008000;">;</span>
    <span style="color:#0600FF;">public</span> <span style="color:#FF0000;">string</span><span style="color:#000000;">[</span><span style="color:#000000;">]</span> Paradigms<span style="color:#008000;">;</span>
    <span style="color:#0600FF;">public</span> <span style="color:#FF0000;">string</span> LatestVersion<span style="color:#008000;">;</span>
    <span style="color:#000000;">[</span>TypeConverter<span style="color:#000000;">(</span><a href="http://www.google.com/search?q=typeof+msdn.microsoft.com"><span style="color:#008000;">typeof</span></a><span style="color:#000000;">(</span>CustomDateTimeConverter<span style="color:#000000;">)</span><span style="color:#000000;">)</span><span style="color:#000000;">]</span>
    <span style="color:#0600FF;">public</span> DateTime InitialRelease<span style="color:#008000;">;</span>
    <span style="color:#000000;">[</span>TypeConverter<span style="color:#000000;">(</span><a href="http://www.google.com/search?q=typeof+msdn.microsoft.com"><span style="color:#008000;">typeof</span></a><span style="color:#000000;">(</span>CustomDateTimeConverter<span style="color:#000000;">)</span><span style="color:#000000;">)</span><span style="color:#000000;">]</span>
    <span style="color:#0600FF;">public</span> DateTime LatestRelease<span style="color:#008000;">;</span>
    <span style="color:#0600FF;">public</span> <span style="color:#FF0000;">float</span> Popularity<span style="color:#008000;">;</span>
<span style="color:#000000;">}</span></pre>
<p>The <em>TypeConverter</em> attributes are completely optional, and are only required when you&#8217;re reading some fields that have unusual formats and whose values you would like to convert to something simpler/more accessible (e.g. a string &#8220;Jun2002&#8243; to a <em>DateTime</em> object in this case). For any field of a type recognisable by the default type converter, you don&#8217;t need to bother, as is shown for the <em>double</em> type. (This actually applies to a very large range of types within the BCL, including <em>System.Drawing.Color</em>, which can be specified in any format that you might use in the propeprty editor of Visual Studio, such as &#8220;DarkRed&#8221;.)</p>
<p>Finally, here&#8217;s a snippet to show how you might actually use the <em>CsvReader&lt;TEntry&gt;</em> class to read from a CSV file. This example reads all entries from the languages.csv file and prints out to the console the names of all functional languages.</p>
<pre class="csharp" style="border:1px solid #d0d0d0;overflow:auto;font-family:monospace;color:#000066;background-color:#f0f0f0;width:100%;margin-bottom:1em;"><span style="color:#0600FF;">using</span> <span style="color:#000000;">(</span>var languagesReader <span style="color:#008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color:#008000;">new</span></a> CsvReader<span style="color:#008000;">&lt;</span>LanguageEntry<span style="color:#008000;">&gt;</span><span style="color:#000000;">(</span><span style="color:#666666;">"language.csv"</span><span style="color:#000000;">)</span><span style="color:#000000;">)</span>
<span style="color:#000000;">{</span>
    var languages <span style="color:#008000;">=</span> from lang <span style="color:#0600FF;">in</span> languagesReader.<span style="color:#0000FF;">ReadAllEntries</span><span style="color:#000000;">(</span><span style="color:#000000;">)</span>
                    where lang.<span style="color:#0000FF;">Paradigms</span>.<span style="color:#0000FF;">Contains</span><span style="color:#000000;">(</span><span style="color:#666666;">"Functional"</span><span style="color:#000000;">)</span>
                    select lang<span style="color:#008000;">;</span>
    <span style="color:#0600FF;">foreach</span> <span style="color:#000000;">(</span>var lang <span style="color:#0600FF;">in</span> languages<span style="color:#000000;">)</span>
        Console.<span style="color:#0000FF;">WriteLine</span><span style="color:#000000;">(</span>lang.<span style="color:#0000FF;">Name</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
<span style="color:#000000;">}</span></pre>
<p>Hopefully that&#8217;s now convinced you that this is the right way to go about reading data entries from files. What this class provides is completely strongly-typed I/O (reading in this case, though it wouldn&#8217;t be very hard to create a similar <em>CsvWriter</em> class), and a declarative manner to defining entry types (or records, to use database termninology).</p>
<p>I&#8217;m not going to delve too deeply into the implementation of the class, but I think it&#8217;s worth highlighting a few specifics. Going back to the code for the class, the first thing to notice is the <em>Initialize</em> method &#8211; this is where much of the interesting stuff is happening. To summarise: it loops over all the public fields of the type specified by <em>TEntry</em>, gets the default type converter for the type of each field (or the one given by <em>TypeConverterAttribute</em>, if it exists), and then stores the <em>FieldInfo</em> along with the <em>TypeConverter</em> in a simple struct. The only other noteworthy point is the call to <em>SetValueDirect</em> in the <em>ReadEntry</em> method. This uses a keyword that&#8217;s almost wholly unknown (and undocumented!) to C# developers by the name of <em>__makeref</em> (there are other related ones by the names of <em>__reftype</em> and <em>__refvalue</em>) &#8211; I was certainly unaware of it before today. The problem that I initially encountered was one of using the <em>SetValue</em> method, which works perfectly well on classes, but presents a unique problem with structs: namely, because they are value-types, and the <em>obj</em> parameter is of type <em>object</em>, the argument must be boxed (wrapped into a reference type) and placed on the heap rather than the stack, meaning that the heap-based copy gets altered, and not the one you passed to the method (which is on the stack)! What the <em>__makeref</em> keyword does is create a <em>TypeReference</em> that directly references the stack-based object and thus allows <em>SetValueDirect</em> to set the field accordingly.</p>
<p>That&#8217;s enough explanation, I think. If you still aren&#8217;t sure about how it works precisely, then feel free to comment on this post. I&#8217;d also be quite happy to hear what anyone thinks of the general design and implementation, too.</p>
<br />Posted in Programming, Projects Tagged: .net, .net 3.5, c#, c# 3.0, comma separated values, csv, file i/o, generics, linq, object initializers, reflection, streamreader, strongly-typed <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/alexreg.wordpress.com/142/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/alexreg.wordpress.com/142/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/alexreg.wordpress.com/142/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/alexreg.wordpress.com/142/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/alexreg.wordpress.com/142/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/alexreg.wordpress.com/142/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/alexreg.wordpress.com/142/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/alexreg.wordpress.com/142/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/alexreg.wordpress.com/142/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/alexreg.wordpress.com/142/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/alexreg.wordpress.com/142/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/alexreg.wordpress.com/142/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/alexreg.wordpress.com/142/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/alexreg.wordpress.com/142/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=alexreg.wordpress.com&amp;blog=3367172&amp;post=142&amp;subd=alexreg&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://alexreg.wordpress.com/2009/05/03/strongly-typed-csv-reader-in-c/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eed60bdfc964ec62cc48aa6020a03d7b?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=PG" medium="image">
			<media:title type="html">Noldorin</media:title>
		</media:content>
	</item>
	</channel>
</rss>
