Search code examples
c#functiongenericsgeneric-programming

Generic function for calling back every kinds of methods with different arguments in C#


I want to have a function which is able to call any function and retrieve a proper value.

these are some examples of what I need:

var IList<Person> = InvokeFunction<IList<Person>>(repositoryPerson.GetAllPerson);

var Persion = InvokeFunction<Person>(repositoryPerson.GetPersonById, 10);

var int = InvokeFunction<int>(repositoryPerson.RunCustomStoreProcedure, 250,"text",521,10);

Solution

  • It can be a generic function:

        public static T InvokeFunction<T>(Func<T> functionName)
        {
            T obj = functionName.Invoke();
            return obj;
        }
    

    How to use:

       public static string method1(string a, string b)
        {
            return a + b;
        }
    
       public static int method2(int id1, string id2, string id3)
        {
            return 0;
        }
    
    
      var result1 = InvokeFunction<string>(() => method1("val1", "val2"));
      var result2 = InvokeFunction<int>(() => method2(123, "val1", "val2"));