Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why I cannot pass a method delegation into GetOrAdd() method in concurrent dictionary?

I have defined the below concurrent dictionary:(because reflection is slow so cached it)

  private static ConcurrentDictionary<Type, MethodInfo> dic = new();

then I wanted to get a method from a type and invoke it.

public void Update(TITarget target)
        {
            var methodInfo = dic.GetOrAdd(typeof(TITarget), ()=> getMethodInfo);

            methodInfo.Invoke(target, new object[] { this });
        }

private static MethodInfo getMethodInfo()
        {
            var types = getInheritanceHierarchy(typeof(TITarget));

            var findUpdateMethod = typeof(TITarget)
                .GetMethods(BindingFlags.Public | BindingFlags.Instance).
                   Where(x => x.Name == "Update");

            var methodInfo = types.Join(
                            findUpdateMethod, t => t.Name,
                            mi => mi.DeclaringType.Name,
                            (t, mi) => mi)
                            .First();
            return methodInfo;
        }

        private static IEnumerable<Type> getInheritanceHierarchy(Type type)
        {
            for (var current = type; current != null; current = current.BaseType)
            {
                yield return current;
            }
        }

but i cannot pass a method to the type of MethodInfo and i got the below compile time error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Severity Code Description Project File Line Suppression State
Error CS1593 Delegate ‘Func<Type, MethodInfo>’ does not take 0 arguments.

how can i fix that issue?

thank you in advance.

>Solution :

dic.GetOrAdd(typeof(TITarget), ()=> getMethodInfo)

You probably want either

 dic.GetOrAdd(typeof(TITarget), getMethodInfo())

or, arguably better:

dic.GetOrAdd(typeof(TITarget), key => getMethodInfo(key))
...
private static MethodInfo getMethodInfo(Type type)
{
            var types = getInheritanceHierarchy(type);
...

The error message is essentially saying that the compiler guesses you want to call GetOrAdd(TKey, Func<TKey,TValue>), but that obviously needs a lambda with the key as an argument.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading