Unit Testing, Agile Development, Leadership & .NET - By Roy Osherove
How does TypeDescriptor.GetProperties(...) differ from withProperties.GetType().GetProperties()?
Jacob: I find it easier to work with, that's all.
You could use this:
new Dictionary<string, string> { { "Name", "Roy" }, { "Country", "Israel" } };
A bit heavier on the syntax, but avoids the reflection.
Andrew: Nice! I hadn't considered that option.
Roy, you can also do this now:
new RouteValueDictionary(new {key1="value1", key2="value2"};
RouteValueDictionary will be populated with the values from the anonymous type. Even though it is called "RouteValueDictionary" it inherits Dictionary<string, object> so is more generally useful assuming you are ok with case insensitivity.
I was going to link this post from Phil Haack's blog, on this subject
haacked.com/.../collection-initializers.aspx
but I see he beat me with his comment :-)
Anyway, on that post you get interesting comments on the possible syntaxes.
> Jacob: I find it easier to work with, that's all.
Plus it uses ICustomTypeDescriptor if you've implemented it. Which is obviously not the case here, but, you know, it's really kinda annoying when Type.GetProperties() is used where TypeDescriptor should be - like in NVelocity.
Pingback from Dictionary To Anonymous Type « Jacob Carpenter’s Weblog
And now you can round-trip back to an anonymous type instance: jacobcarpenter.wordpress.com/.../dictionary-to-anonymous-type
People who don't like reflection will hate this version:
static public IDictionary<string, object> MakeDictionary(object o)
{
Type type = o.GetType();
return type.GetProperties()
.Select(n => n.Name)
.ToDictionary(k => k, k => type.GetProperty(k).GetValue(o, null));
}