1

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();
}
FaizanHussainRabbani
  • 3,256
  • 3
  • 26
  • 46
Kandey
  • 23
  • 1
  • 4
  • Is this the sort of thing you mean : https://stackoverflow.com/questions/4181668/execute-c-sharp-code-at-runtime-from-code-file – PaulF Feb 15 '18 at 17:05
  • No, you can't inject a method to a class on the fly, the most simmilar you can do is to create on the fly a class which inherits from the class type and replace the instance with a new one. – Gusman Feb 15 '18 at 17:09

2 Answers2

1

The closest you can get is to use the Dynamic Language Runtime features with an ExpandoObject.

dynamic d = new ExpandoObject();
d.Quack = (Action)(() => System.Console.WriteLine("Quack!!!"));
d.Quack(); 

There are many downsides to this though, including lack of InteliSense, no compiler errors when accessing non-existent members, and poor performance,

Bradley Uffner
  • 16,641
  • 3
  • 39
  • 76
0

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;
}
Kandey
  • 23
  • 1
  • 4