Thursday, November 01, 2007

I sure hope so! I noticed this quite some time ago when I first saw the syntax for anonymous types in C#. Being a lover of JavaScript, I quite like the ability to do things in C# in a manner consistent with the syntax I am used to using in JavaScript (my current favorite programming language, especially thanks to MochiKit). The syntax I refer to is partly alluded to in this post by Eilon Lipton (first time I have ever heard of Eilon), where he talks about substituting an anonymous type for a Dictionary<string, string>, using said Dictionary for setting attributes on HTML tags he is creating in C#. Sound familiar? I mentioned something similar in my post yesterday.

To illustrate the syntax I keep referring to, here is what I am used to doing in JavaScript, particularly with MochiKit - let's say I want to create a div element programmatically (and let's spit it out as HTML so we can better get the gist of things):

 toHTML(DIV({id:"myDiv", class:"myCssClass"}, P({ style:"font-weight:bold" }, "Hello World!")));

The HTML rendered looks like:

 <div class="myCssClass" id="myDiv"> <p style="font-weight: bold;">Hello World!</p> </div>

So, rather than declaring a the JavaScript function "DIV" or "P" (which create div and paragraph DOM elements, respectively) with every possible option as a parameter to said function (e.g. id, style, class, etc.), you simply pass in an anonymous object which contains values for the properties you care about setting. This is a fairly typical way of doing things in JavaScript, and despite the protests from the academic portion of my brain as well as other developers, I would love to be able to do the same in C#.

 

Technorati Tags: , , ,

posted on Thursday, November 01, 2007 11:38:15 AM (Mountain Standard Time, UTC-07:00)  #    Comments [0] Trackback