Dictionary with Func as key
c#, dictionary, func
Solution
No, C# constructs a new delegate instance whenever a lambda is used so you wouldn't be able to use it as a consistent key. Example:
Func<int, int> f = x => x*x + 1;
Func<int, int> g = x => x*x + 1;
Console.WriteLine(f.Equals(g)); // prints False
This would then make usage awkward as a dictionary key unless you had some other way to always obtain the same instance.
Edit:
Eric Lippert's answer here indicates that the compiler is allowed to detect the lambdas are the same (although it typically does not). Either way a lambda/delegate makes a poor choice for a key.
Problem
I am wondering if this is a sane choice of key for a dictionary? What I want to do is use an expression as the key in a dictionary, something like: ``` var map3 = new Dictionary<Func<int, bool>, int>(); map3.Add((x) => x % 2 == 0, 1); map3.Add((x) => x % 10 == 0, 2); // ... var key = map3.Keys.SingleOrDefault(f => f(2)); // key = (x) => x % 2 // map3[key] = 1 ``` The idea being this is a cleaner way than having big if-else or switch statements. Does this make sense? Will it work? Is there an simpler way?