<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://devlicio.us/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>Sergio Pereira : Language-Envy</title><link>http://devlicio.us/blogs/sergio_pereira/archive/tags/Language-Envy/default.aspx</link><description>Tags: Language-Envy</description><dc:language>en</dc:language><generator>CommunityServer 2008.5 SP1 (Build: 31106.3070)</generator><item><title>Language Envy - C# needs Ranges</title><link>http://devlicio.us/blogs/sergio_pereira/archive/2010/01/02/language-envy-c-needs-ranges.aspx</link><pubDate>Sat, 02 Jan 2010 10:55:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:54862</guid><dc:creator>sergiopereira</dc:creator><slash:comments>14</slash:comments><description>	&lt;p&gt;
		As soon as I started learning Ruby, a few years ago, I got immediately hooked 
		on its &lt;a href="http://ruby-doc.org/core/classes/Range.html"&gt;&lt;code&gt;Range&lt;/code&gt;&lt;/a&gt; class. 
		I could not believe I had been programming in .NET without them for so long.
	&lt;/p&gt;

	&lt;p&gt;
		I like to think of range objects as the specification for a &lt;code&gt;for&lt;/code&gt;
		loop, packaged in an object that can be passed around. That&amp;#39;s not the whole story, though.
		Ranges also represent sequences or intervals, which can be queried for intersection or
		containment. See the following Ruby sample code.
	&lt;/p&gt;

		&lt;pre name="code" class="ruby:nogutter"&gt;#declare a Range object
summer_months = 6..9
#enumerate it
summer_months.each {|m| puts &amp;quot;#{Date.new(2000, m, 1).strftime(&amp;#39;%B&amp;#39;)} is a Summer month.&amp;quot; }
#other handy features
summer_months.include? 7 # ==&amp;gt; true
summer_months.to_a # ==&amp;gt; [6, 7, 8, 9]  (converted to array)&lt;/pre&gt;


	&lt;h3&gt;I needed that in C#&lt;/h3&gt;
	&lt;p&gt;
		That was back when the CLR 2.0 was just about to be released and I ended up
		writing my own Range&lt;/code&gt; class. I have used this class in a handful of
		projects since then and I&amp;#39;m still surprised that we don&amp;#39;t have it in the
		standard .NET class library. The closest thing I&amp;#39;m aware of is the method
		&lt;a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.range.aspx"&gt;&lt;code&gt;System.Linq.Enumerable.Range(int, int)&lt;/code&gt;&lt;/a&gt;,
		which is rather limited (it only enumerates integers one by one).
	&lt;/p&gt;

	&lt;p&gt;
		Here&amp;#39;s the code that I came up with, which has served me well for many years. First 
		an abstract base class. I&amp;#39;ll omit parts of the code for brevity but I&amp;#39;ll give you 
		a link for the complete source at the end.
	&lt;/p&gt;

	&lt;pre name="code" class="csharp:nogutter"&gt;public abstract class RangeBase&amp;lt;T&amp;gt; : IEnumerable&amp;lt;T&amp;gt; where T : IComparable
{
  public T Start { get; set; }
  public T End { get; set; }

  protected RangeBase(T start, T end)
  {
    // ... snip ...
  }

  protected abstract T GetNextItem(T currentItem);

  public IEnumerator&amp;lt;T&amp;gt; GetEnumerator()
  {
    T item = Start;

    while (true)
    {
      if (item.CompareTo(End) &amp;gt; 0)
        break;

      yield return item;

      item = GetNextItem(item);
    }
  }


  IEnumerator IEnumerable.GetEnumerator()
  {
    return GetEnumerator();
  }

  public bool Intersects(RangeBase&amp;lt;T&amp;gt; otherRange)
  {
    // ... snip ...
  }

  public bool Contains(RangeBase&amp;lt;T&amp;gt; otherRange)
  {
    // ... snip ...
  }

  public bool Contains(T element)
  {
    return (Start.CompareTo(element) &amp;lt;= 0) &amp;amp;&amp;amp; (End.CompareTo(element) &amp;gt;= 0);
  }
}&lt;/pre&gt;

	&lt;p&gt;
		There&amp;#39;s also a generic concrete type and a bunch of the more common
		implementations for convenience.
	&lt;/p&gt;

	&lt;pre name="code" class="csharp:nogutter"&gt;public class Range&amp;lt;T&amp;gt; : RangeBase&amp;lt;T&amp;gt; where T : IComparable
{
  public Func&amp;lt;T, T&amp;gt; GetNext { get; private set; }

  public Range(T start, T end, Func&amp;lt;T, T&amp;gt; getNext)
    : base(start, end)
  {
    GetNext = getNext;
  }

  protected override T GetNextItem(T currentItem)
  {
    return GetNext(currentItem);
  }
}

public class Int32Range : RangeBase&amp;lt;int&amp;gt;
{
  public Int32Range(int start, int end) : base(start, end){}
  protected override int GetNextItem(int currentItem)
  {
    return currentItem + 1;
  }
}

public class Int64Range : RangeBase&amp;lt;long&amp;gt; { /* ... snip ... */ }
public class DayRange : RangeBase&amp;lt;DateTime&amp;gt; { /* ... snip ... */ }
public class HourRange : RangeBase&amp;lt;DateTime&amp;gt; { /* ... snip ... */ }
//...etc...&lt;/pre&gt;


	&lt;h3&gt;Coding with Ranges&lt;/h3&gt;
	&lt;p&gt;
		With the above classes I can write code that is similar in functionality to the
		Ruby version.
	&lt;/p&gt;
	&lt;pre name="code" class="csharp:nogutter"&gt;//declare a range of numbers
var summerMonths = new Int32Range(6, 9);
//enumerate it
foreach(var m in summerMonths) 
  Console.WriteLine(new DateTime(2000, m, 1).ToString(&amp;quot;MMMM&amp;quot;) + &amp;quot; is a Summer month.&amp;quot;);
//other handy features
summerMonths.Contains(7); // ==&amp;gt; true
summerMonths.Contains(new Int32Range(7, 8)); // ==&amp;gt; true
summerMonths.ToArray(); // ==&amp;gt; [6, 7, 8, 9]  (using LINQ extensions)&lt;/pre&gt;

	&lt;p&gt;
		We can also use the generic &lt;code&gt;Range&lt;/code&gt; type to create less orthodox
		iterations, like a sequence of dates that repeat &lt;i&gt;every other week&lt;/i&gt;:
	&lt;/p&gt;

&lt;pre name="code" class="csharp:nogutter"&gt;var startDate = new DateTime(2010, 1, 1);
var endDate = startDate.AddMonths(3);
var appointmentDates = new Range&amp;lt;DateTime&amp;gt;(startDate, endDate, d =&amp;gt; d.AddDays(14));
appointmentDates.ToArray(); 
// ==&amp;gt; [ 1/1/2010, 1/15/2010, 1/29/2010, 
//          2/12/2010, 2/26/2010, 3/12/2010, 3/26/2010 ]&lt;/pre&gt;

	&lt;p&gt;
		The complete source for these classes and even some unit tests can be found
		&lt;a href="http://github.com/sergiopereira/juicy/blob/master/src/Juicy.Core/Ranges.cs"&gt;here&lt;/a&gt;.
	&lt;/p&gt;

	&lt;h3&gt;Other implementations&lt;/h3&gt;
	&lt;p&gt;
		Of course I was not the first to implement a Range class in C#. A quick search
		yielded at least a 
		&lt;a href="http://www.pluralsight.com/community/blogs/dbox/archive/2005/04/24/7690.aspx"&gt;couple&lt;/a&gt;
		of &lt;a href="http://andyclymer.blogspot.com/2009/03/ruby-ranges-in-net.html"&gt;articles&lt;/a&gt; with
		different approaches to the same goal.
	&lt;/p&gt;
 &lt;p&gt;Another indication that ranges are a popular data structure is the fact that F# has them too.
With luck we will see ranges in a future version of the .NET framework. Oh, 
and since we are wishing for things. let&amp;#39;s hope they introduce range literals in C# at that same time.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=54862" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/.NET/default.aspx">.NET</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Ruby/default.aspx">Ruby</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Series/default.aspx">Series</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Language-Envy/default.aspx">Language-Envy</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Juicy/default.aspx">Juicy</category></item><item><title>Language Envy - Juicy, a simple webserver</title><link>http://devlicio.us/blogs/sergio_pereira/archive/2009/04/13/language-envy-juicy-a-simple-webserver.aspx</link><pubDate>Tue, 14 Apr 2009 04:02:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:46007</guid><dc:creator>sergiopereira</dc:creator><slash:comments>17</slash:comments><description>	
	&lt;p&gt;
	Many times when I&amp;#39;m writing JavaScript code with  Ajax calls I don&amp;#39;t have an 
	URL to call and get the data yet. Or sometimes I have an URL that gives me
	valid data and I need to test the code against invalid data or some other
	variation that I don&amp;#39;t have handy.
	&lt;/p&gt;

	&lt;h3&gt;WEBrick&lt;/h3&gt;

	&lt;p&gt;
	In these situations, instead of creating a temporary ASP.NET application,
	I learned to love using Ruby and the adorable simplicity of 
	&lt;a href="http://www.webrick.org/"&gt;WEBrick&lt;/a&gt;. Imagine that I needed
	an URL that simulated latency on the server.
	&lt;/p&gt;

&lt;pre name="code" class="ruby"&gt;require &amp;#39;webrick&amp;#39;
include WEBrick

server = HTTPServer.new( :Port =&amp;gt; 2000 )

server.mount_proc(&amp;quot;/getData&amp;quot;){|req, res|
  res.body = &amp;quot;{result: &amp;#39;ok&amp;#39;, accountId: 123}&amp;quot;
  res[&amp;#39;Content-Type&amp;#39;] = &amp;quot;application/json&amp;quot;
  delay = req.query[&amp;#39;delay&amp;#39;] || &amp;quot;0&amp;quot;
  sleep(delay.to_i)
}

trap(&amp;quot;INT&amp;quot;){ server.shutdown }
server.start&lt;/pre&gt;
  
	&lt;p&gt;
	After running the script I can open use the URL &lt;i&gt;http://localhost:2000/getData?delay=5&lt;/i&gt; 
	in my Ajax call and, after a delay of five seconds, the JSON string &lt;i&gt;{result: &amp;#39;ok&amp;#39;, accountId: 123}&lt;/i&gt;
	will be returned. The server will stay there, in a console window, running until I kill it with CTRL+C.
	&lt;/p&gt;

	&lt;p&gt;
	I could add more mount points on that server for as many test URLs as I wish. I find this incredibly practical.
	&lt;/p&gt;

	&lt;h3&gt;I wish there was something as simple in .NET&lt;/h3&gt;

	&lt;p&gt;
	Well, I couldn&amp;#39;t find anything as easy in .NET. The few offerings I found were not as straight forward. Some
	of the alternatives are distributed in .msi files, which makes them less convenient, especially
	for integration testing or JavaScript unit testing (which is my end goal.)
	&lt;/p&gt;

	&lt;h3&gt;Hello Juicy&lt;/h3&gt;
	&lt;p&gt;
	Envy sometimes makes you move forward. I played around with sockets and the HTTP protocol
	and ended up with a library that looks promising. See that same code written using
	the &lt;code&gt;Juicy.DirtCheapDaemons.Http.HttpServer&lt;/code&gt; class, a.k.a. the &lt;b&gt;Juicy Web Server&lt;/b&gt;.
	&lt;/p&gt;

&lt;pre name="code" class="csharp"&gt;using System;
using System.IO;
using System.Threading;
using Juicy.DirtCheapDaemons.Http;

  class Program
  {
    static void Main(string[] args)
    {
      HttpServer server = new HttpServer{ PortNumber = 2000 };
      server.Start();

      server.Mount(&amp;quot;/getData&amp;quot;, 
        (req, resp) =&amp;gt;
          {
            resp.Output.Write(&amp;quot;{result: &amp;#39;ok&amp;#39;, accountId: 123}&amp;quot;);
            resp[&amp;quot;Content-Type&amp;quot;] = &amp;quot;application/json&amp;quot;;
            var delay = int.Parse(req.QueryString[&amp;quot;delay&amp;quot;] ?? &amp;quot;0&amp;quot;);
            Thread.Sleep(1000 * delay);
          }
      );

      Console.WriteLine(&amp;quot;Press enter to stop server&amp;quot;);
      Console.ReadLine();
      server.Shutdown();
    }
  }&lt;/pre&gt;

&lt;p&gt;
	There are a few things more that can be done with &lt;code&gt;HttpServer&lt;/code&gt;.
&lt;/p&gt;

&lt;pre name="code" class="csharp"&gt;//mounting virtual path with a lambda (shown in previous example)
server.Mount(&amp;quot;/virtual/path&amp;quot;, (req, resp) =&amp;gt; DoSomethingWith(req, resp));

//mounting virtual path to serve static files
server.Mount(&amp;quot;/virtual/path&amp;quot;, @&amp;quot;c:\some\directory&amp;quot;);

//hiding a virtual path
server.Mount(&amp;quot;/virtual/path/subdir&amp;quot;, new ResourceNotFoundHandler());&lt;/pre&gt;

	&lt;p&gt;
	As it is, &lt;code&gt;HttpServer&lt;/code&gt; supports only &lt;i&gt;GET&lt;/i&gt; requests.
	The plan is to add more support (for features that make sense in a
	unit testing scenario) with time.
	&lt;/p&gt;
	&lt;p&gt;

	I obviously don&amp;#39;t envision Juicy becoming a full-fledged web server
	that I can recommend using in a live web site. But I can see it
	being helpful in the scenarios I&amp;#39;ve just described and for testing
	in general.
	&lt;/p&gt;

	&lt;h3&gt;I&amp;#39;m sold. Where can I get it?&lt;/h3&gt;
	&lt;p&gt;
	This project is hosted at GitHub: &lt;a href="http://github.com/sergiopereira/juicy/tree/master"&gt;http://github.com/sergiopereira/juicy/tree/master&lt;/a&gt;,
        where you can download the source directly or even clone the repository :
	&lt;/p&gt;

&lt;pre&gt;c:\projects&amp;gt;git clone git://github.com/sergiopereira/juicy.git&lt;/pre&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=46007" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/.NET/default.aspx">.NET</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Ruby/default.aspx">Ruby</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript/default.aspx">JavaScript</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Language-Envy/default.aspx">Language-Envy</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Juicy/default.aspx">Juicy</category></item><item><title>Language Envy - String Interpolation</title><link>http://devlicio.us/blogs/sergio_pereira/archive/2009/01/17/language-envy-string-interpolation.aspx</link><pubDate>Sun, 18 Jan 2009 01:50:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:43774</guid><dc:creator>sergiopereira</dc:creator><slash:comments>19</slash:comments><description>
&lt;b&gt;Language Envy:&lt;/b&gt;
This post is part of &lt;a href="http://devlicio.us/blogs/sergio_pereira/archive/tags/Language+Envy/default.aspx"&gt;a series&lt;/a&gt;
where I wish C# had a particular feature I came to like when working with other programming languages.


&lt;p&gt;
	Every time I have to produce a string in C# the little
	groaning chimp that lives inside my head pulls his hair out. It&amp;#39;s
	about time we had a better way of doing this.
&lt;/p&gt;

&lt;p&gt;
	We all use &lt;code&gt;string.Format&lt;/code&gt; to make these string concatenations
	more readable, but it&amp;#39;s still too easy to get the order wrong or miss one
	of the argument values and get an exception. JetBrain&amp;#39;s Resharper can be helpful here,
	giving hints when you have too many or too few arguments in a call to
	&lt;code&gt;string.Format&lt;/code&gt;.
&lt;/p&gt;


&lt;h3&gt;So what am I whining about?&lt;/h3&gt;

&lt;p&gt;
	When you need to create a string that mixes literals with variables in 
	&lt;a href="http://www.php.net/string#language.types.string.syntax.double"&gt;PHP&lt;/a&gt;
	(or &lt;a href="http://www.ruby-doc.org/docs/ProgrammingRuby/html/intro.html#S2"&gt;Ruby&lt;/a&gt;, 
	 or &lt;a href="http://boo.codehaus.org/String+Interpolation"&gt;Boo&lt;/a&gt;,
	 or &lt;a href="http://savage.net.au/Perl/html/interpolation.html"&gt;Perl&lt;/a&gt;, etc) it&amp;#39;s so
	 much easier to type, read and maintain than in C#:
&lt;/p&gt;

&lt;pre name="code" class="php"&gt;&amp;lt;?php
	$price = 12.34;
	$product = &amp;quot;DVD Media&amp;quot;;
	echo &amp;quot;$product costs $price&amp;quot;;
	//ouputs: DVD Media costs 12.34
?&amp;gt;&lt;/pre&gt;


&lt;p&gt;
	Although this would be enough to get a lot done, the interpolation syntax can
	help with more complicated expressions beyond simple variables:
&lt;/p&gt;
&lt;pre name="code" class="php"&gt;&amp;lt;?php
	$order = $user-&amp;gt;getLastOrder();
	echo &amp;quot;The first item in the order was {$order-&amp;gt;item[0]}.&amp;quot;;
	//ouputs: The first item in the order was DVD Media.
?&amp;gt;&lt;/pre&gt;


&lt;p&gt;
	One interesting thing to note is that this is a syntax for combining
	expression values and literals. The interpolation isn&amp;#39;t evaluated in
	strings that already exist and are passed in (like some user input.)
	In other words, the interpolation happens at parsing time, where the
	string is declared. The parser will not look into an existing string
	and replace tokens that look like variables &amp;mdash; at least not
	without you explicitly asking it to do so.
&lt;/p&gt;


&lt;p&gt;
	In PHP the interpolation goes a little further. Just for the sake of
	curiosity, check this out.
&lt;/p&gt;
&lt;pre name="code" class="php"&gt;&amp;lt;?php
	$var1 = 1000;
	$name = &amp;#39;var1&amp;#39;;
	//recursive interpolation:
	echo &amp;quot;The value of the variable named $name is {${$name}}&amp;quot;;
	//outputs: This is the value of the var named var1 is 1000 
?&amp;gt;&lt;/pre&gt;

&lt;p&gt;
	Wouldn&amp;#39;t it be nice to have such syntax in C#? The string would probably
	need to be taken care of at compile time, so a statement like this:
&lt;/p&gt;

&lt;pre name="code" class="csharp"&gt;//DOESN&amp;#39;T WORK YET. JUST A DAYDREAM
var text = &amp;quot;The price of a ${product.Name} is ${product.Price}.&amp;quot;;&lt;/pre&gt;

&lt;p&gt;
	At compile time would be treated as if it had been written as follows.
&lt;/p&gt;

&lt;pre name="code" class="csharp"&gt;var text = &amp;quot;The price of a &amp;quot; + product.Name + 
           &amp;quot; is &amp;quot; + product.Price + &amp;quot;.&amp;quot;;
// OR ...
var text = string.Concat(&amp;quot;The price of a &amp;quot;, product.Name, 
           &amp;quot; is &amp;quot;, product.Price, &amp;quot;.&amp;quot;);&lt;/pre&gt;


&lt;p&gt;
	Done like the example above this would be a backwards compatibility problem.
	I&amp;#39;m sure it&amp;#39;s possible to put some symbol before the opening double quote to
	make this compatible.
&lt;/p&gt;
&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=43774" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/.NET/default.aspx">.NET</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Series/default.aspx">Series</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Language-Envy/default.aspx">Language-Envy</category></item><item><title>Language Envy - hash literals</title><link>http://devlicio.us/blogs/sergio_pereira/archive/2009/01/05/language-envy-hash-literals.aspx</link><pubDate>Mon, 05 Jan 2009 08:38:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:43597</guid><dc:creator>sergiopereira</dc:creator><slash:comments>1</slash:comments><description>
&lt;b&gt;Language Envy:&lt;/b&gt;
This post is part of &lt;a href="http://devlicio.us/blogs/sergio_pereira/archive/tags/Language+Envy/default.aspx"&gt;a series&lt;/a&gt;
where I wish C# had a particular feature I came to like when working with other programming languages.


&lt;p&gt;
	It&amp;#39;s easy to let a small language feature go unnoticed. The more I spend
	time writing JavaScript and Ruby, the more one little detail shows itself
	loud and clear when I go back to my trusty C# (well, it shows itself by not being absent, 
if that makes any sense.)
&lt;/p&gt;

&lt;p&gt;
	The little language detail I&amp;#39;m writing about today is the literal syntax
	for hashes. Especially in JavaScript, because all objects are just hashes
	on steroids, which makes the literal object syntax become one and the same
	with the hash literals.
&lt;/p&gt;
&lt;p&gt;
	In JavaScript it&amp;#39;s easy as 1-2-3. It&amp;#39;s not surprising so many libraries are
	adopting hash parameters.
&lt;/p&gt;

		&lt;pre name="code" class="js"&gt;//Prototype.js sample
var elements = { success: &amp;#39;myDiv&amp;#39;, failure: &amp;#39;errorDiv&amp;#39; };
var ajax = new Ajax.Updater(
	elements, 
	&amp;#39;getData.aspx&amp;#39;, 
	{ method: &amp;#39;get&amp;#39;, onFailure: reportError }
	);
//jQuery sample (jQuery UI)
$(&amp;#39;#fromDate&amp;#39;).datepicker({rangeSelect: true, firstDay: 1});
$(&amp;quot;#search&amp;quot;).autocomplete(&amp;quot;/product/find&amp;quot;,
	{ autoFill: true, delay: 10, minChars: 3 }
	);&lt;/pre&gt;

&lt;p&gt;
	Now, I understand that part of the popularity of hashes in JavaScript 
	and Ruby is due to the loose typing of these languages. But if the syntax
	wasn&amp;#39;t light, APIs like the above ones would be much more painful to use.  
&lt;/p&gt;

&lt;p&gt;
	C# 3 does have a hash syntax (or, more accurately, a dictionary one.)
	Unfortunately, dictionary initializers, although being a step forward,
	still leave noise to be removed.
&lt;/p&gt;

&lt;pre name="code" class="csharp"&gt;// hypothetical search API 
var books = FindWithCriteria&amp;lt;Product&amp;gt;(
              new Dictionary&amp;lt;string,object&amp;gt;
              {
                {&amp;quot;Category&amp;quot;, Category.Books},
                {&amp;quot;MinPrice&amp;quot;, 33.45},
                {&amp;quot;MaxPrice&amp;quot;, 50.00},
                {&amp;quot;Contains&amp;quot;, &amp;quot;asp.net&amp;quot;}
              });&lt;/pre&gt;

&lt;p&gt;
	Hmmm, no, thanks. Maybe that&amp;#39;s the reason we are starting to see some
	APIs that use (abuse?) anonymous objects and reflection to create hashes.
&lt;/p&gt;

&lt;pre name="code" class="csharp"&gt;// hypothetical search API 
var books = FindWithCriteria&amp;lt;Product&amp;gt;(
              new { 
                Category = Category.Books,  
                MinPrice = 33.45,
                MaxPrice = 50.00, 
                Contains = &amp;quot;asp.net&amp;quot; 
              });&lt;/pre&gt;
&lt;p&gt;
	This last one doesn&amp;#39;t look so bad on the surface, but we know what is going on
	under the covers so it&amp;#39;s like &lt;i&gt;&lt;a href="http://www.urbandictionary.com/define.php?term=putting%20lipstick%20on%20a%20pig"&gt;putting lipstick on a pig&lt;/a&gt;&lt;/i&gt;. If, instead of using reflection at run-time, the compiler had
	support for converting the above anonymous object into a 
	&lt;code&gt;IDictionary&amp;lt;string,object&amp;gt;&lt;/code&gt;, then we would have a more
	convenient and efficient way of creating hashes. Maybe it&amp;#39;s too late to introduce a feature
        like that while maintaining backwards compatibility.
&lt;/p&gt;
&lt;p&gt;
	I believe when you add a language feature that is elegantly designed (i.e. clean and unnoticeable,)
	it becomes popular more quickly &amp;mdash; just like 
      &lt;a href="http://devlicio.us/blogs/sergio_pereira/archive/tags/Designing+With+Lambdas/default.aspx"&gt;what is 
   happening with lambdas&lt;/a&gt; . 
       The existing alternatives for creating hashes in C# 3
	are still too noisy or inefficient to be integrated in our code without reducing
	the readability or incurring a performance penalty. 
&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=43597" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/.NET/default.aspx">.NET</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Ruby/default.aspx">Ruby</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Series/default.aspx">Series</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript/default.aspx">JavaScript</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Language-Envy/default.aspx">Language-Envy</category></item><item><title>Language Envy - episode 0</title><link>http://devlicio.us/blogs/sergio_pereira/archive/2008/12/24/language-envy-episode-0.aspx</link><pubDate>Wed, 24 Dec 2008 22:32:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:43512</guid><dc:creator>sergiopereira</dc:creator><slash:comments>5</slash:comments><description>&lt;p&gt;
	Although C# is the language that I can call myself proficient enough to make a living these days,
	there are other languages that I have to use for specific tasks (like JavaScript, SQL, XSLT.) 
	I also like using other general purpose languages for pure exploration or pet projects. I&amp;#39;d
	include Ruby, ObjectiveC and PHP in this group.
&lt;/p&gt;
&lt;p&gt;
	When using other languages it often happens that I encounter features that I wish C# had or
	that the C#-equivalent was as easy (it works both ways &amp;mdash; I miss some C# feature on &lt;i&gt;the 
	other side&lt;/i&gt; as well.)
&lt;/p&gt;
&lt;p&gt;
	In &lt;a href="http://devlicio.us/blogs/sergio_pereira/archive/tags/Language+Envy/default.aspx"&gt;this 
        series of undetermined length&lt;/a&gt; I will be posting some of the items from my wish list as 
	I remember them.
&lt;/p&gt;

&lt;h3&gt;The &lt;code&gt;case&lt;/code&gt; statement&lt;/h3&gt;

&lt;p&gt;
	To start things off, let&amp;#39;s check out C#&amp;#39;s case statement, straight from 
	&lt;a href="http://msdn.microsoft.com/en-us/library/aa664749(VS.71).aspx"&gt;the language specification&lt;/a&gt;.
&lt;/p&gt;

&lt;pre name="code"&gt;switch-statement:
    switch   (   expression   )   switch-block
switch-block:
    {   switch-sectionsopt   }
switch-sections:
    switch-section
    switch-sections   switch-section
switch-section:
    switch-labels   statement-list
switch-labels:
    switch-label
    switch-labels   switch-label
switch-label:
    case   &lt;b&gt;constant-expression&lt;/b&gt;   : // &amp;lt;-- line 14
    default   :&lt;/pre&gt;

&lt;p&gt;
	I know that doesn&amp;#39;t look like C# code. What I&amp;#39;d like to point is in line 14. The
	expression in each &lt;code&gt;case&lt;/code&gt; label has to be a constant. I&amp;#39;m sure that helps
	making the &lt;code&gt;switch&lt;/code&gt; statement compile to a very efficient MSIL code, but
	let&amp;#39;s consider what we are missing because of that.
&lt;/p&gt;

&lt;p&gt;
	Here&amp;#39;s a sample of what you can do in a Ruby &lt;code&gt;case&lt;/code&gt; expression. 
&lt;/p&gt;


&lt;b&gt;SIDE NOTE: &lt;/b&gt;
The hawk-eyed reader will catch the terminology difference here. Many language
constructs that are mere &lt;i&gt;statements&lt;/i&gt; in C# are &lt;i&gt;expressions&lt;/i&gt; in Ruby.
But that&amp;#39;s not the feature I&amp;#39;ll write about today. Maybe in a future installment.


&lt;pre name="code" class="ruby"&gt;Months = %w(JAN FEB MAR APR MAY\
        JUN JUL AGO SEP OCT NOV DEC)

def get_month(value)
  case value
    when Date # class name (instance of?)
      return Months[value.month - 1]

    when /\d{4}-(\d{2})-\d{2}/ # Regular expression (matches ?)
      return Months[$1.to_i  - 1]

    when 1..12  # Range of values (contained ?)
      return Months[value - 1]

  end
end

puts get_month(Date.today)
puts get_month(&amp;quot;2008-10-20&amp;quot;)
puts get_month(8)&lt;/pre&gt;


&lt;p&gt;
	As you can hopefully see in the above example, the expressions in 
	each &lt;code&gt;when&lt;/code&gt; statement do not need to be constants
	(class names like &lt;code&gt;Date&lt;/code&gt; are constants, by the way)
&lt;/p&gt;
&lt;p&gt;
	Ruby defines the &lt;code&gt;===&lt;/code&gt; (triple equal) comparison operator
	that can be overriden in each class and is used in the &lt;code&gt;case&lt;/code&gt;
	expression to test each &lt;code&gt;when&lt;/code&gt; condition. This is usually read
	as &lt;i&gt;&amp;quot;when value matches with this expression here...&amp;quot;&lt;/i&gt;.
&lt;/p&gt;
&lt;p&gt;
	Not surprisingly, the built-in classes in Ruby do override the triple
	equal operator to add a more meaningful implementation for it.
	&lt;code&gt;Range&lt;/code&gt; matches the values that are within the range. &lt;code&gt;RegExp&lt;/code&gt; matches
	values that agree with the regular expression, &lt;code&gt;Class&lt;/code&gt; objects
	match values that are instances of that class, etc.
&lt;/p&gt;
&lt;p&gt;
	I use this feature all the time and it&amp;#39;s so convenient that I&amp;#39;d be thrilled to 
	see it in C# one day.	
&lt;/p&gt;

&lt;h3&gt;So, what is my suggestion?&lt;/h3&gt;

&lt;p&gt;
	I wouldn&amp;#39;t be a real programmer if I didn&amp;#39;t try to sell my own suggestion, would I? Since
	&lt;code&gt;IComparable&lt;/code&gt; is taken and means something different, I was thinking of maybe
	something like this.
&lt;/p&gt;

&lt;pre name="code" class="csharp"&gt;public interface ICanMatch&lt;/code&gt;
{
  bool Match(object value);
}

public interface ICanMatch&amp;lt;T&amp;gt;&lt;/code&gt;
{
  bool Match(T value);
}
// I know, I know. That interface name doesn&amp;#39;t have much of a chance
// of sticking. But, hey, that&amp;#39;s _my_ wish list ;).&lt;/pre&gt;

&lt;p&gt;
	The C# compiler would check if any of the &lt;code&gt;case&lt;/code&gt; labels uses an 
	&lt;code&gt;ICanMatch&lt;/code&gt; expression and invoke its &lt;code&gt;Match&lt;/code&gt; method
	passing the &lt;code&gt;switch&lt;/code&gt; value. If it returns &lt;code&gt;true&lt;/code&gt; we
	have a match and the &lt;code&gt;case&lt;/code&gt;&amp;#39;s code block is executed.
&lt;/p&gt;
&lt;p&gt;
  Another alternative would be to add a new method to the &lt;code&gt;System.Object&lt;/code&gt;
  that defaults to simply calling &lt;code&gt;Equals&lt;/code&gt;. The thought of adding a new
  method there is a little bit too frightening for me.
&lt;/p&gt;
&lt;p&gt;
	At any rate, I can only dream of the day I&amp;#39;d be able to write:
&lt;/p&gt;

&lt;pre name="code" class="csharp"&gt;public string GetMonth(dynamic value)
{
	switch(value)
	{
		case typeof(DateTime):
			return value.ToString(&amp;quot;MMM&amp;quot;);
		case new Regex(@&amp;quot;\d{4}-\d{2}-\d{2}&amp;quot;):
			return DateTime.Parse(value).ToString(&amp;quot;MMM&amp;quot;);
		case new MyRange(1, 12):
			return new DateTime(2000, value, 1).ToString(&amp;quot;MMM&amp;quot;);
	}
	return null;
}&lt;/pre&gt;

&lt;p&gt;
  This example is too simple and obviously contrived (a few method overloads or plain polymorphism  
 would have taken care of that,) but I still hope you can see the value of this suggestion.
&lt;/p&gt;
&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=43512" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/.NET/default.aspx">.NET</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Ruby/default.aspx">Ruby</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Series/default.aspx">Series</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Language-Envy/default.aspx">Language-Envy</category></item></channel></rss>