I'm trying to compile a code at runtime and create an instance of one of the classes in it, but I get some errors when using c# 6+ features like string interpolation. Here is the code I'm using to compile:
using (var cs = new CSharpCodeProvider())
{
var assembly = typeof(MyType).Assembly;
var cp = new CompilerParameters()
{
GenerateInMemory = false,
GenerateExecutable = false,
IncludeDebugInformation = true,
};
if (Environment.OSVersion.Platform.ToString() != "Unix") cp.TempFiles = new TempFileCollection(Environment.GetEnvironmentVariable("TEMP"), true);
else cp.TempFiles.KeepFiles = true;
cp.ReferencedAssemblies.Add("System.dll");
cp.ReferencedAssemblies.Add("System.Core.dll");
cp.ReferencedAssemblies.Add(assembly.Location);
CompilerResults cr;
if (Directory.Exists(path))
{
string[] files = Directory.GetFiles(path, "*.cs", SearchOption.AllDirectories);
cr = cs.CompileAssemblyFromFile(cp, files);
}
else cr = cs.CompileAssemblyFromFile(cp, new string[] { path });
if (cr.Errors.HasErrors)
throw new Exception("Compliation failed, check your code.");
var types = cr.CompiledAssembly.GetTypes();
var myType = types.Where(x => x.GetInterfaces().Contains(typeof(MyType))).FirstOrDefault();
if (myType == null)
throw new TypeLoadException("Could not find MyType class");
return (MyType)cr.CompiledAssembly.CreateInstance(myType.FullName);
}
Now if I try to compile a code that uses something like:
string name = $"My name is {name}";
I get this exception:
Unexpected character '$'