Search code examples
c#.netvisual-studiocompiler-errorsruntime-compilation

C# Runtime Compilation error: Type 'Double' and 'Math' could not be found/does not exist in current context


I have added "System.dll" to the compiler parameter referenced assemblies.I also noticed that adding to "Using System" to the codeToCompile OR using "System.Math" or "System.Double" works fine.Not sure what's wrong.

    using Microsoft.CSharp;
    using System;
    using System.CodeDom.Compiler;
    using System.Text;
    using System.Windows.Forms;

     private void onLoadPlugin(object sender, EventArgs e)
    {
        string codeToCompile =
     @"

class TestPlugin
{
    public string ArithmeticOperator
    {
        get { return ""X^2""; }
    }
    public double PerformCalculation(string value)
    {
        Double var = Double.Parse(value);
        if (var == 0)
            return 0;
        return Math.Pow(var, 2);
    }
}
        ";

        CSharpCodeProvider provider = new CSharpCodeProvider();//new Dictionary<String, String> { { "CompilerVersion", "v4.0" } });
        CompilerParameters parameters = new CompilerParameters();
        parameters.ReferencedAssemblies.Add("System.dll");//This doesn't seem to be working

            parameters.GenerateInMemory = false;
            parameters.GenerateExecutable = false;
            parameters.OutputAssembly = "TestPlugin.dll";

        CompilerResults results = provider.CompileAssemblyFromSource(parameters, codeToCompile);
        if (results.Errors.Count != 0)
            throw new Exception("Mission Failed");


    }

Solution

  • Using "using...":

    using System;
    class TestPlugin
    {
        public string ArithmeticOperator
        {
            get { return ""X^2""; }
        }
        public double PerformCalculation(string value)
        {
            Double var = Double.Parse(value);
            if (var == 0)
                return 0;
            return Math.Pow(var, 2);
        }
    }
    

    or not using "using...":

    class TestPlugin
    {
        public string ArithmeticOperator
        {
            get { return ""X^2""; }
        }
        public double PerformCalculation(string value)
        {
            System.Double var = System.Double.Parse(value);
            if (var == 0)
                return 0;
            return System.Math.Pow(var, 2);
        }
    }