Skip to main content
GameDev.net gamedev.net
🔒 Locked

[.net] Implementing a map/assoc array as parameter.

Started by Lucidquiet Jun 28, 2009 at 1:46 PM 0 replies 1k views
Original Post
Lucidquiet
Lucidquiet
So I've been kicking around a number way to render HTML as coded (no .aspx files here). I'd like the basic signature to look something like this:

Tag.Create("div", "class", "myClass", "My textual context or more tags");
Even better would be something like this:

Tag.Create("div", {"class" = "myClass"}, "My textual context or more tags");
First thought was to use an anonymous class, but this has both performance problems and type problems. Another approach might be this:

Dictionary<string,string> Map = delegate(params string[] args) {
  // pair up args as key/value pairs
};
Tag.Create("div", Map(k1,v1,k2,v2), "My test");
There are probably a number of different way to do this, but I would like one that requires a minimal amount of additional code and doesn't have to rely on an even length array. And yes performance is an issue for this rendering as well. Thanks, L-
"Education is when you read the fine print; experience is what you get when you don't." -Pete Seegerwww.lucid-edge.net
alex_myrpg
alex_myrpg
Unfortunately C# does support collection intializers but not "dictionary initializers", which means there's no syntactically elegant way to do this. I would recommend passing the attributes as name/value pairs (strings separated by a single char delimeter).

You could define your Create method as such:

public void Create(string tagName, string content, params string[] attributePairs){    var attribs = attributePairs.Select(val =>        {            var parts = val.Split(new char[] {':'}, 2);            return new {Name = parts[0], Value = parts[1].TrimStart()};        }).ToDictionary(item => item.Name, item => item.Value);    var cssClass = attribs["class"]; // example usage    // ...}


This means you could call the method as follows:

Create("div", "text content/more tags", "class: myClass", "style: background: white;");


Given that the C# language does not have built-in support for maps/dictionaries (unlike &#106avascript for example), I'm fairly convinced this is the nicest way to do it.<br><br>Hope this helps.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.