C# 3.0 Feature of the Day: Dictionary Initialisation

Today I found myself needing to write a simple property that scrapes all of the values off of the form and returns them as a dictionary (keyed by the field name). Here is the C# 2.0 way of doing that:

public IDictionary<string, object> FormValues
{
get
{
IDictionary<string, object> values = new Dictionary<string, object>();
values.Add("FirstName", GivenNameField.Text);
values.Add("Surname", SurnameField.Text);
values.Add("Gender", GenderField.SelectedValue);
return values;
}
}

And here is the C# 3.0 way using collection initialisation over the dictionary:

public IDictionary<string, object> FormValues
{
get
{
return new Dictionary<string, object>
{
{ "FirstName", GivenNameField.Text },
{ "Surname", SurnameField.Text },
{ "Gender", GenderField.SelectedValue }
};
}
}

I really like this. There is so much less noise in the C# 3.0 way. This seems to be one of the goals of C# 3.0. To reduce code noise.


Do you have a favourite new language feature?

asp-netc--3-0c-
Posted by: Mike Minutillo
Last revised: 27 May, 2011 02:42 PM History

Comments

No comments yet. Be the first!

No new comments are allowed on this post.