So, I got a comment on the last post about hashes from lambdas (from Andrey Shchekin)... It pointed out the fact that you don't need to use expressions at all... which hilights an observation that I hadn't made myself - such that the lambda parameter names are available in the generated delegate... which of course makes perfect sense!
So given:
Func<string, T> func = Name => "Value";
You can get the lambda parameter "Name" from the function delegate by calling:func.Method.GetParameters()[0].Name (would return "Name")Here's the revised Hash method from Andrey:
public Dictionary<string, T> Hash<T>(params Func<string, T>[] args)where T : class{ var items = new Dictionary<string, T>(); foreach (var func in args) { var item = func(null); items.Add(func.Method.GetParameters()[0].Name, item); } return items;}
very elegant and simple :)
He even did some stats, which I suspect are probably a lot more accurate then my inital observations:For 10000 consecutive calls:
[Test]public void HashTwoLevelDict(){ Dictionary<string, Dictionary<string, object>> config = this.Hash<object>( (Connection, DriverClass) => typeof(SqlClientDriver), (Dialect, DialectClass) => typeof(MsSql2000Dialect), (Connection, Provider) => typeof(DriverConnectionProvider), (Connection, ConnectionString) =>"Data Source=.;Initial Catalog=test;Integrated Security=SSPI");
Assert.AreEqual(typeof(SqlClientDriver), config["Connection"]["DriverClass"]);}