Initializing dictionaries is a pain in the neck. I've seen many clever ways to make it painless. Here goes yet another one.
This it's not my idea, I saw it a couple of days ago in some API but I can't remember where. This is my very simple implementation.
public static IDictionary<string, TValue> Map<TValue>(this IDictionary<string, TValue>
dictionary, Expression<Func<object, TValue>> pair)
var key = pair.Parameters.Name;
var eval = pair.Compile().Invoke(new object);
dictionary[key] = eval;
Still we'll need some guard clauses and clean up.
var bag = new Dictionary<string, object>()
.Map(Id => 1)
.Map(Name => "Tom Bombadil")
.Map(CreatedOn => DateTime.Today)
.Map(CreatedBy => "root");
Assert.That(bag["Name"], Is.EqualTo("Tom Bombadil"));