user1492051
user1492051

Reputation: 906

Can i run c# files at run time

i have multiple c# classes, they have completely different functionalities and i write a lot of them daily and i don't want to build everytime i add a class, but all classes share a function which is called Run() and it takes no parameters also the constructors never take a parameter, is it possible get a c# file from a path compile it and then making an instance of it and calling the Run() from that instance?

all i do to make a class do its job is

var x = new xclass(); //the constructor never takes a param
x.Run();

but what i want to do is

var x = CreateInstance(getClassbyPath("xxx.cs"));
x.Run();

Upvotes: 0

Views: 109

Answers (2)

Mihai Hantea
Mihai Hantea

Reputation: 1743

Check this Dynamic-Code-Integration-with-CodeDom

Small example from the above link

class Program
{
  static void Main( string[] args )
  {
      Test1();
  }
  private static void Test1()
  {
     //
     // Create an instance of type Foo and call Print
     //
     string FooSource = @"
        class Foo
        {
           public void Print()
           {
              System.Console.WriteLine(""Hello from class Foo"");
           }
        }";

     Assembly assembly = CompileSource(FooSource);
     object myFoo = assembly.CreateInstance("Foo");
     // myFoo.Print(); // - Print not a member of System.Object
     // ((Foo)myFoo).Print(); // - Type Foo unknown
  }
}


private static Assembly CompileSource( string sourceCode )
{
   CodeDomProvider cpd = new CSharpCodeProvider();
   CompilerParameters cp = new CompilerParameters();
   cp.ReferencedAssemblies.Add("System.dll");
   cp.ReferencedAssemblies.Add("ClassLibrary1.dll");
   cp.GenerateExecutable = false;
   // Invoke compilation.
   CompilerResults cr = cpd.CompileAssemblyFromSource(cp, sourceCode);

   return cr.CompiledAssembly;
}

Update: Another way you can do it by using a plugin architecture, as starting poing check this answers. You can put the plugins in a folder and detect when new plugins are added and load and run them. But this implies to create a new dll for each of your class and implement the common interface.

Upvotes: 1

Håkan Fahlstedt
Håkan Fahlstedt

Reputation: 2095

Take a look at the System.CodeDom namespace.

Upvotes: 2

Related Questions