Nobody cannot reject that Ruby are one of becoming mainstream languages nowadays. With the fame of Rails, it does not just push Ruby far like this but inspires many other frameworks to do the same.
Of course, C# and ASP.NET are also impacted from Rails too. I wrote about the extension method, one of new C# 3.0 feature set, that makes C# look like Ruby than before. Instead of typing DateTime.Now.AddMinutes(30) to get 30 minutes later time, 30.minutes.later does the trick. Today, I’ve crossed a blog post that utilizes the anonymous type to make ASP.NET Web Form even more looks like Rails View. Actually, he didn’t intentionally make it but I see the similarity as I read on.
If you want to create a hyperlink in Rails, you have two choices, create it manually or use helper. The former works with more performance at the cost of flexibility and the latter is the vice versa.
<a href="url here">The Link</a>
<%= link_to 'The Link', :url=>'url here' %>
Like Rails, you also have 2 choices in ASP.NET Web form to create a link, use HyperLink control or create it by hand. While Rails offers the flexibility in using helper to create link, controller and action can be provided to produce the url, ASP.NET provides you with a little advantage over the manual way, the Application Path, which I’ll discuss in this post.
To reproduce the same as above example with ASP.NET, we use this code.
<a href="url here">The Link</a>
<asp:HyperLink id="aHyperLink" runat="server" NavigateUrl="url here">The Link</asp:HyperLink>
Note that it has significantly more characters to type.
Let’s say that I want to crate a hyperlink with class attribute. I can add a attribute as an option to the link_to helper like this.
<%= link_to 'The Link', :url=>'url here' , :class=>"cssclass"%>
Although this can be achieve easily in ASP.NET by using HyperLink control, creating a helper maybe a good idea.Now we get this instead.
<%= HtmlHelper.GetHtmlLink('The Link', new { url = "url here", class = "cssclass")} %>
With anonymous types and property initializes feature, we can set up a property dictionary for hyperlink that’ll be passed to method GetHtmlLink easily. As the result, we get a more rails-like helper in ASP.NET. The two only problems for this thing are slowness and practicality. This approach heavily relies on Reflection to imply the anonymous type at runtime. Reflection related processes, which function at runtime, are always slower than compile time counter part. Importantly, you can get this by using HyperLink control by adding a cssclass property which is faster and more practical.
Now the ASP.NET Web Form is looked more like Rails.
PS. If you want have a try, go to Eilon Lipton’s blog to get the working code. As a reminder, you also need .NET Framework 3.5 to get C# 3.0.
