Saturday, October 3, 2009

Using C# 3.0 Anonymous Types as Dictionaries

public static string GetHtmlLink(string text, IDictionary properties)
{
//do some work
}

//too many lines and less efficient
Dictionary values = new Dictionary();
values.Add("key1", "value1");
values.Add("key2", "value2");
values.Add("key3", "value3");
GetHtmlLink("Click me", values);

//better
MyParams myParams = new MyParams { Key1 = "value1", Key2 = "value2", Key3 = "value3" };
GetHtmlLink("Click me", myParams);

Sample link: <%= HtmlHelpers.GetHtmlLink("My Site", new { @class = "someStyle", href = "http://www
And it'll render this HTML:
Sample link: <a class="someStyle" href="http://www.example.org">My Sitea>

<br />
Sample URL: http://www.example.org/search?query=kitten's+mittens&mode=details
from
http://weblogs.asp.net/leftslipper/archive/2007/09/24/using-c-3-0-anonymous-types-as-dictionaries.aspx


No comments:

Post a Comment