Search code examples
c#lambdastaticrefactoringgeneric-method

How to use STATIC class value with LIST or LAMBDA EXPRESSION?


This is my sample code.

public class Sample
{
    public void Main()
    {
        Execute01<DB_MS_A>();
        Execute02<DB_MS_A>();

        Execute01<DB_MS_B>();
        Execute02<DB_MS_B>();

        Execute01<DB_MS_C>();
        Execute02<DB_MS_C>();
    }
           
    public void Execute01<DbModel>()
        where DbModel : IDatabaseModel
    {
        // do something...
    }

    public void Execute02<DbModel>()
        where DbModel : IDatabaseModel
    {
        // do something...
    }
}

Not to waste code lines, I want to modify Main method code like below.

    public void Main()
    {
        var dbList = new List<dynamic>() {
            DB_MS_A,
            DB_MS_B,
            DB_MS_C
        };

        dbList.ForEach(db => {
            Execute01<db>();
            Execute02<db>();
        });
    }

But it seems impossible to add static value to List. Also Delivering static value as lambda arguments is not possible.

Is there any way for method Refactoring?


Solution

  • I think you can simply use a list of type:

    var listInputType = new []{
            typeof(string), 
            typeof(int),
    }; 
    

    But I don't think you can pass run time type to generique as they need compile type.
    But we can use reflexion like in this SO question: C# use System.Type as Generic parameter.

    public class Program
    {
        public static void Main()
        {
            var listInputType = new []{
                    typeof(string), 
                    typeof(int),
            }; 
            
            foreach(var myType in listInputType){
                typeof(Program).GetMethod("M1").MakeGenericMethod(myType).Invoke(null, null);
                typeof(Program).GetMethod("M2").MakeGenericMethod(myType).Invoke(null, null);
            }
        }
    
        public static void M1<t>()
        {
            Console.WriteLine($"M1<{typeof(t).Name}>()");
        }
    
        public static void M2<t>()
        {
            Console.WriteLine($"M2<{typeof(t).Name}>()");
        }
    }
    

    C# online demo