I've set up a simple console application
In Program.cs
I'm trying to get script to compile while inheriting a base class
using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Data;
namespace TestingInConsole
{
public class BaseClass { }
class Program
{
static void Main(string[] args)
{
var scriptText = @"
namespace TestingInConsole
{
public class Test : BaseClass
{
}
}";
var compileOptions = new CompilerParameters();
compileOptions.GenerateInMemory = true;
var compiler = new CSharpCodeProvider();
var compileResult = compiler.CompileAssemblyFromSource(compileOptions, scriptText);
if (compileResult.Errors.Count > 0)
throw new Exception($"Error in script: {compileResult.Errors[0].ErrorText}\nLine: {compileResult.Errors[0].Line}");
var assembly = compileResult.CompiledAssembly;
dynamic script = assembly.CreateInstance($"TestingInConsole.Test");
// TODO: add Run() function to Test class
DataSet dataSetResult = script.Run();
}
}
}
But I get the error
System.Exception: 'Error in script: The type or namespace name 'BaseClass' could not be found (are you missing a using directive or an assembly reference?) Line: 4'
after line: if (compileResult.Errors.Count > 0)
Questions
Is it possible for CSharpCodeProvider scripts like this to inherit base classes?
Or should I create new function in Program.cs
to check if the script instance has proper functions (that I would in other case put in the base class)?
EDIT 1: Suggestions from comments
I've created new library project in my solution, added empty public class BaseClass
to it, added a reference to it in Program.cs
.
And this is what I've changed in Program.cs
var compileOptions = new CompilerParameters();
var assembliesPath = AppDomain.CurrentDomain.BaseDirectory;
compileOptions.ReferencedAssemblies.Add(assembliesPath + "TestLibrary.dll");
compileOptions.GenerateInMemory = true;
I've rebuilt both projects, but I still get the same error.