Question

I'm building a pseudocode translator and compiler. It translates the pseudocode to code by performing several string operations, then it uses the CSharpCodeProvider class to compile it, and finally it tries to run it.

After a few tests, in the case that the translated/output code is the following:

using System;
using System.Collections.Generic;

public class TranslatedProgram
{
    public static void ReadLine(ref int destiny)
    {
        destiny = int.Parse(Console.ReadLine());
    }
    public static void InsertInStack(ref Stack<int> originalStack, int value)
    {
        Console.WriteLine("Inserting the value " + value + " to the stack.");
        originalStack.Push(value);
        foreach (int current in originalStack)
        {
            Console.WriteLine("|" + current);
        }
        Console.WriteLine("_______");
    }
    public static void Main()
    {
        int value = new int();
        Stack<int> data = new Stack<int>();
        ReadLine(ref value);
        InsertInStack(ref data, value);
    }
}

When the application sends this code to the CSharpCodeProvider, it doesn't compile. In the compilerResults, I get the following error: "The type or namespace name 'Stack' could not be found (are you missing a using directive or an assembly reference?)" (CS0246)

BUT when I put this code, exactly as it is, inside a new project from the VS IDE, it works perfectly.

Any guess?

Thanks.

Edit:

I'm calling the CSharpCodeProvider compiler from VB by doing the following:

Private Sub CompileButton_Click(sender As Object, e As EventArgs) Handles CompileButton.Click
        If ApplicationSaveFileDialog.ShowDialog = Windows.Forms.DialogResult.OK Then
            Dim Compiler As New Microsoft.CSharp.CSharpCodeProvider
            Dim Results As System.CodeDom.Compiler.CompilerResults
            Results = Compiler.CompileAssemblyFromSource(New CodeDom.Compiler.CompilerParameters With {.GenerateExecutable = True, .OutputAssembly = ApplicationSaveFileDialog.FileName}, CodeTextBox.Text)
            If Results.Errors.Count = 0 Then
                Shell(ApplicationSaveFileDialog.FileName)
            Else
                For Each Exception As System.CodeDom.Compiler.CompilerError In Results.Errors
                    ExceptionsTextBox.AppendText(Exception.ErrorText)
                Next
            End If
        End If
    End Sub

How could I include a reference to System.dll?

Was it helpful?

Solution

Make sure that, when you compile, you have a reference to the dll that holds Stack<>, which is System.dll.

You can add a reference by using property ReferencedAssemblies of the CompilerParameters class:

CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("System.dll");
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerResults cr = provider.CompileAssemblyFromFile(cp, "MyFile.cs");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top