Posted by & filed under .Net.

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:

WithAdd 10.0144ms
WithLambdas 9713.968ms
WithLambdasConstantsOnly 240.3456ms
WithDelegates 30.0432ms

Now what about multiple parameters… so far I can’t think
of any uses I would have for it… perhaps a 2 level configuration
dictionary?

[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"]);
}

Who knows… I look forward to seeing how Lambdas get used and
abused for non-functional programming tasks :)

Comments are closed.