Search code examples
c#extension-methodscode-injection

Extending a Class with a method on runtime


Is there a possibility to add methods to an existing class at run time?

I want to create a List of Testcase objects and I don't like to create for each Testcase an object. So I like to use a unique object without any method for the Test cases without any procedure info. I want to add this method afterwards.

Code:

public class Testcollection
{
    public List<TestCase> TestcaseList = new List<TestCase>();
    public string title;
    public Testcollection(string Title)
    {
        title = Title;
    }
}
public class TestCase
{
    public string title;
    public TestCase(string Title)
    {
        title = Title;
    }
}
public class initTestcollection
{
    public Testcollection T1 = new Testcollection("Collection1");
    public Testcollection T2 = new Testcollection("Collection2");
    public void AddTestCases()
    {
        T1.TestcaseList.Add(new TestCase("Test1"));
        T1.TestcaseList.Add(new TestCase("Test2"));
    }
    //Pseudocode
    public void inject_method_toT1()
    {
    Console.WriteLine("injected code A");
    }
    public void inject_method_toT2()
    {
    Console.WriteLine("injected code B");
    }
    //constructor
    public initTestcollection()
    {
        AddTestCases();
        inject_method_toT1();
        inject_method_toT2()
    }

}

void Main()
{
 Testcollection MyCollection = new initTestblocks();
 MyCollection.T1.TestcaseList[0].inject_method_toT1();
 MyCollection.T1.TestcaseList[1].inject_method_toT2();
}

Solution

  • I found the following post: Dynamically assign method / Method as variable with that I could a assign a "dummy" Method to my Testcase Class and could assign a Test workflow to it on the runtime. For someone who has the same usecase the code:

    public class TestCase
    {
        public string title;
        public TestCase(string Title)
        {
            title = Title;
        }
        public Action dummyMethod{ get; set; }
    }
    public void realMethod()
    {
        System.Console.WriteLine("testSuccesfull");
    }
    public initTestcollection()
    {
        AddTestCases();
        T1.TestcaseList[0].dummyMethod= realMethod;
    }