Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8879311
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T19:55:23+00:00 2026-06-14T19:55:23+00:00

My application works with loading dll’s dynamically, based on settings from the database (file,

  • 0

My application works with loading dll’s dynamically, based on settings
from the database (file, class and method names). To facilitate, expedite and reduce the use of reflection I would like to have a cache….

Following the idea that using:

 MethodInfo.Invoke

Is nothing performative ( Reflection Performance – Create Delegate (Properties C#))
I would like to translate any call to methods. I thought of something that would work like this:

public static T Create<T>(Type type, string methodName) // or
public static T Create<T>(MethodInfo info) // to use like this:
var action = Create<Action<object>>(typeof(Foo), "AnySetValue");

One requirement is that all the parameters, can be object.

I’m trying to deal with expressions, and so far I have something like this:

    private void Sample()
    {
        var assembly = Assembly.GetAssembly(typeof(Foo));

        Type customType = assembly.GetType("Foo");

        var actionMethodInfo = customType.GetMethod("AnyMethod");
        var funcMethodInfo = customType.GetMethod("AnyGetString");
        var otherActionMethod = customType.GetMethod("AnySetValue");
        var otherFuncMethodInfo = customType.GetMethod("OtherGetString");

        var foo = Activator.CreateInstance(customType);
        var actionAccessor = (Action<object>)BuildSimpleAction(actionMethodInfo);
        actionAccessor(foo);

        var otherAction = (Action<object, object>)BuildOtherAction(otherActionMethod);
        otherAction(foo, string.Empty);

        var otherFuncAccessor = (Func<object, object>)BuildFuncAccessor(funcMethodInfo);
        otherFuncAccessor(foo);

        var funcAccessor = (Func<object,object,object>)BuildOtherFuncAccessor(otherFuncMethodInfo);
        funcAccessor(foo, string.Empty);
    }

    static Action<object> BuildSimpleAction(MethodInfo method)
    {
        var obj = Expression.Parameter(typeof(object), "o");

        Expression<Action<object>> expr =
            Expression.Lambda<Action<object>>(
                Expression.Call(
                    Expression.Convert(obj, method.DeclaringType),
                    method), obj);

        return expr.Compile();
    }

    static Func<object, object> BuildFuncAccessor(MethodInfo method)
    {
        var obj = Expression.Parameter(typeof(object), "o");

        Expression<Func<object, object>> expr =
            Expression.Lambda<Func<object, object>>(
                Expression.Convert(
                    Expression.Call(
                        Expression.Convert(obj, method.DeclaringType),
                        method),
                    typeof(object)),
                obj);

        return expr.Compile();

    }

    static Func<object, object, object> BuildOtherFuncAccessor(MethodInfo method)
    {
        var obj = Expression.Parameter(typeof(object), "o");
        var value = Expression.Parameter(typeof(object));

        Expression<Func<object, object, object>> expr =
            Expression.Lambda<Func<object, object, object>>(
                    Expression.Call(
                        Expression.Convert(obj, method.DeclaringType),
                        method,
                        Expression.Convert(value, method.GetParameters()[0].ParameterType)), 
                        obj, value);

        return expr.Compile();

    }

    static Action<object, object> BuildOtherAction(MethodInfo method)
    {
        var obj = Expression.Parameter(typeof(object), "o");
        var value = Expression.Parameter(typeof(object));

        Expression<Action<object, object>> expr =
            Expression.Lambda<Action<object, object>>(
                Expression.Call(
                    Expression.Convert(obj, method.DeclaringType),
                    method,
                    Expression.Convert(value, method.GetParameters()[0].ParameterType)),
                obj,
                value);

        return expr.Compile();
    }

public class Foo
{
    public void AnyMethod() {}

    public void AnySetValue(string value) {}

    public string AnyGetString()
    {            return string.Empty;        }

    public string OtherGetString(string value)
    {            return string.Empty;        }
}

Is there any way to simplify this code? (I believe it is possible to create a method only using generic..) And when you have 3, 4, 5, any parameters as I do?


I was thinking, what if there was something like this:

https://codereview.stackexchange.com/questions/1070/generic-advanced-delegate-createdelegate-using-expression-trees

but I’ll have more one parameter (in action or function), this parameter (first parameter) an object to perform.
Is this possible?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T19:55:24+00:00Added an answer on June 14, 2026 at 7:55 pm

    I have made a sample program that fulfills all your requirements (I think!)

    class Program
    {
        class MyType
        {
            public MyType(int i) { this.Value = i; }
    
            public void SetValue(int i) { this.Value = i; }
    
            public void SetSumValue(int a, int b) { this.Value = a + b; }
    
            public int Value { get; set; }
        }
    
        public static void Main()
        {
            Type type = typeof(MyType);
    
            var mi = type.GetMethod("SetValue");
    
            var obj1 = new MyType(1);
            var obj2 = new MyType(2);
    
            var action = DelegateBuilder.BuildDelegate<Action<object, int>>(mi);
    
            action(obj1, 3);
            action(obj2, 4);
    
            Console.WriteLine(obj1.Value);
            Console.WriteLine(obj2.Value);
    
            // Sample passing a default value for the 2nd param of SetSumValue.
            var mi2 = type.GetMethod("SetSumValue");
    
            var action2 = DelegateBuilder.BuildDelegate<Action<object, int>>(mi2, 10);
    
            action2(obj1, 3);
            action2(obj2, 4);
    
            Console.WriteLine(obj1.Value);
            Console.WriteLine(obj2.Value);
    
            // Sample without passing a default value for the 2nd param of SetSumValue.
            // It will just use the default int value that is 0.
            var action3 = DelegateBuilder.BuildDelegate<Action<object, int>>(mi2);
    
            action3(obj1, 3);
            action3(obj2, 4);
    
            Console.WriteLine(obj1.Value);
            Console.WriteLine(obj2.Value);
        }
    }
    

    DelegateBuilder class:

    public class DelegateBuilder
    {
        public static T BuildDelegate<T>(MethodInfo method, params object[] missingParamValues)
        {
            var queueMissingParams = new Queue<object>(missingParamValues);
    
            var dgtMi = typeof(T).GetMethod("Invoke");
            var dgtRet = dgtMi.ReturnType;
            var dgtParams = dgtMi.GetParameters();
    
            var paramsOfDelegate = dgtParams
                .Select(tp => Expression.Parameter(tp.ParameterType, tp.Name))
                .ToArray();
    
            var methodParams = method.GetParameters();
    
            if (method.IsStatic)
            {
                var paramsToPass = methodParams
                    .Select((p, i) => CreateParam(paramsOfDelegate, i, p, queueMissingParams))
                    .ToArray();
    
                var expr = Expression.Lambda<T>(
                    Expression.Call(method, paramsToPass),
                    paramsOfDelegate);
    
                return expr.Compile();
            }
            else
            {
                var paramThis = Expression.Convert(paramsOfDelegate[0], method.DeclaringType);
    
                var paramsToPass = methodParams
                    .Select((p, i) => CreateParam(paramsOfDelegate, i + 1, p, queueMissingParams))
                    .ToArray();
    
                var expr = Expression.Lambda<T>(
                    Expression.Call(paramThis, method, paramsToPass),
                    paramsOfDelegate);
    
                return expr.Compile();
            }
        }
    
        private static Expression CreateParam(ParameterExpression[] paramsOfDelegate, int i, ParameterInfo callParamType, Queue<object> queueMissingParams)
        {
            if (i < paramsOfDelegate.Length)
                return Expression.Convert(paramsOfDelegate[i], callParamType.ParameterType);
    
            if (queueMissingParams.Count > 0)
                return Expression.Constant(queueMissingParams.Dequeue());
    
            if (callParamType.ParameterType.IsValueType)
                return Expression.Constant(Activator.CreateInstance(callParamType.ParameterType));
    
            return Expression.Constant(null);
        }
    }
    

    How it works

    The core is the BuildDelegate method:

    static T BuildDelegate<T>(MethodInfo method)

    • T is the delegate type you want to create.
    • method is the MethodInfo of the method you want to be called by the generated delegate.

    Example call: var action = BuildDelegate<Action<object, int>>(mi);

    Rules for parameters:

    • If the method passed is an instance method, first parameter of the generated delegate will accept the instance of the object, that contains the method itself. All other parameter will be passed to the method.

    • If the method passed is a static method, then all parameters of the generated delegate will be passed to the method.

    • Missing parameters will have default values passed.

    • Extra parameters will be discarded.
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm working on a Silverlight application that works with WCF services. While loading the
My application works with the MVC model. The model contains a Bindable class (BindableItemsClass)
I have an C# form application that use an access database. This application works
I have to create a class that will load all the dll's from repository
Okay, I am trying to add a .dll file to my application in Visual
I'm building an application that uses the Oracle.DataAccess.dll to connect to a database to
C# - Loading image from file resource in different assembly I have a PNG
Application works fine. I can access everything in debug except for an Array Adapter
My application works for iOS 5.1 but for iOS 6 simulator I get the
My application works fine on the dev server but when I upload it fails

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.