Search code examples
c#streamwritercodedomsystem-codedom-compiler

C# GenerateCodeFromCompileUnit is Generating Code with Special Characters [Microsoft.CSharp.CSharpCodeProvider]


I am using GenerateCodeFromCompileUnit and IndentedTextWriter to Generate Code from C# Source File. Doing this I am able to Generate a .cs file. But I am seeing a special character @ is inserted before every declared variable and Function Return types. Here's is my code.

I am using a Class to Hold Function details to be Inserted.

Dim provider As Microsoft.CSharp.CSharpCodeProvider
Dim options = New System.CodeDom.Compiler.CompilerParameters
options.ReferencedAssemblies.Add("System.dll")
options.GenerateExecutable = False
options.GenerateInMemory = True
options.IncludeDebugInformation = True
options.OutputAssembly = "FunctionEvaluated.dll"

Dim compileUnit As System.CodeDom.CodeCompileUnit
compileUnit = New CodeDom.CodeCompileUnit
Dim codeNamespace = New CodeDom.CodeNamespace("NewNamespace")

compileUnit.Namespaces.Add(codeNamespace)

Dim classForCompile = New CodeDom.CodeTypeDeclaration("NewAction")
codeNamespace.Types.Add(classForCompile)

Dim functionToEvaluate = New CodeDom.CodeMemberMethod()

Dim returnType As CodeDom.CodeTypeReference

If functionClass.FunctionNameAndType.Select(Function(fn) fn.Value)(0).ToString() = "void" Then
    returnType = New CodeDom.CodeTypeReference("void")
Else

    returnType = New CodeDom.CodeTypeReference(functionClass.FunctionNameAndType.Select(Function(fn) fn.Value)(0).ToString())
End If

Dim parameterExpressionCollection = New CodeDom.CodeParameterDeclarationExpressionCollection()

For Each ip In functionClass.FunctionNameIP


    For Each fnIP In ip.Value
        Dim parameterExpression As CodeDom.CodeParameterDeclarationExpression
        parameterExpression = New CodeDom.CodeParameterDeclarationExpression(fnIP.Value.ToString(), fnIP.Key.ToString())

        parameterExpressionCollection.Add(parameterExpression)
    Next
Next

functionToEvaluate.Name = functionClass.FunctionNameAndType.Select(Function(fn) fn.Key)(0).ToString()
functionToEvaluate.ReturnType = returnType
functionToEvaluate.Parameters.AddRange(parameterExpressionCollection)


classForCompile.Members.Add(functionToEvaluate)

provider = New Microsoft.CSharp.CSharpCodeProvider
Dim sourceFile As String
sourceFile = "FunctionEvaluated.cs"
Dim tw As IndentedTextWriter = New IndentedTextWriter(New StreamWriter(sourceFile, False), vbTab)
provider.GenerateCodeFromCompileUnit(compileUnit, tw, New CodeGeneratorOptions())
tw.Close()

Output

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace NewNamespace {
    
    
    public class NewAction {
        
        private @int functionAdd(@int b, @int a) {
        }
    }
}

Solution

  • I believe your problem is in the lines

    New CodeDom.CodeTypeReference(functionClass.FunctionNameAndType.Select(Function(fn) fn.Value)(0).ToString())
    

    and

    parameterExpression = New CodeDom.CodeParameterDeclarationExpression(fnIP.Value.ToString(), fnIP.Key.ToString())
    

    I suspect that using a string to specify a native type is causing the DOM to believe this is a user-defined type 'int' and masks it with an @ to prevent the native int from being used. From https://en.wikipedia.org/wiki/C_Sharp_syntax#Keywords

    If an identifier is needed which would be the same as a reserved keyword, it may be prefixed by the @ character to distinguish it

    To make sure that the output uses a native type like int you could try using

    new CodeTypeReference(typeof(int))
    

    In other words, use a real Type with the public CodeTypeReference(Type type); constructor.

    To get a real Type from a string naming the type, you can use the Type.GetType(String) function.

    So try this:

    New CodeDom.CodeTypeReference(Type.GetType(functionClass.FunctionNameAndType.Select(Function(fn) fn.Value)(0).ToString()))
    

    and

    parameterExpression = New CodeDom.CodeParameterDeclarationExpression(Type.GetType(fnIP.Value.ToString()), fnIP.Key.ToString())