Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

CodeGen - Turn a CodeCompileUnit to VB.Net (or C#) code

0.00/5 (No votes)
16 Aug 2015 1  
A quick-and-dirty function to display the VB.NET code resultant from any given code compile unit

Introduction

When working with Roslyn and Code Gen it is useful to be able to visualise the code graph you have built as raw VB.Net code (since most of us are accustomed to thinking in code).

Utility function:

This snippet converts the compile unit to readable VB.Net code:

''' <summary>
''' Turn whatever code compile unit is passed in to VB.Net code in a multi-line string
''' </summary>
''' <param name="codeUnitToShow">
''' The program graph (partial or complete) to turn into VB code
''' </param>
''' <returns></returns>
Public Shared Function ToVBCodeString(ByVal codeUnitToShow As CodeCompileUnit) As String

    Using provider As New VBCodeProvider
        'Visual Basic specific initialisation
        Dim vbNetOptions As New CodeDom.Compiler.CodeGeneratorOptions()
        vbNetOptions.BlankLinesBetweenMembers = True

        Dim sbRet As New System.Text.StringBuilder
        Using textWriter As New System.IO.StringWriter(sbRet)
            Using codeWriter As New IndentedTextWriter(textWriter)
                provider.GenerateCodeFromCompileUnit(codeUnitToShow, codeWriter, vbNetOptions)
            End Using
        End Using
        Return sbRet.ToString()
    End Using


End Function

Usage:

For example if I assemble a code graph thus:

Imports System.CodeDom

'...

        Dim interfaceObj As CodeTypeDeclaration = CodeGeneration.InterfaceCodeGeneration.InterfaceDeclaration("Duncan's Interface")
        Dim interfaceHolder As New CodeCompileUnit
        Dim nsMain As New CodeNamespace("test")
        interfaceHolder.Namespaces.Add(nsMain)
        nsMain.Types.Add(interfaceObj)

And given the following utility function to create the interface:

Public Shared Function InterfaceDeclaration(ByVal entityName As String) As CodeTypeDeclaration

    Dim interfaceDeclarationRet As CodeTypeDeclaration = New CodeTypeDeclaration(ModelCodeGenerator.MakeInterfaceName(entityName))
    interfaceDeclarationRet.IsPartial = True
    interfaceDeclarationRet.IsInterface = True

    Return interfaceDeclarationRet

End Function

The resulting output would be:

'------------------------------------------------------------------------------
' <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>
'------------------------------------------------------------------------------

Option Strict Off
Option Explicit On


Namespace test
    
    Partial Public Interface IDuncan_s_Interface
    End Interface
End Namespace

C# version

To convert a code snippet to C# code the equivalent utility function would be:

''' <summary>
''' Turn whatever code compile unit is passed in to C# code in a multi-line string
''' </summary>
''' <param name="codeUnitToShow">
''' The program graph (partial or complete) to turn into C# code
''' </param>
Public Shared Function ToCSharpCodeString(ByVal codeUnitToShow As CodeCompileUnit) As String

    Using provider As New CSharpCodeProvider
        Dim cSharpOptions As New CodeDom.Compiler.CodeGeneratorOptions()
        cSharpOptions.BlankLinesBetweenMembers = True
        cSharpOptions.BracingStyle = "C" ' Change this to "Block" to have the open brace on the current line (freak)

        Dim sbRet As New System.Text.StringBuilder
        Using textWriter As New System.IO.StringWriter(sbRet)
            Using codeWriter As New IndentedTextWriter(textWriter)
                provider.GenerateCodeFromCompileUnit(codeUnitToShow, codeWriter, cSharpOptions)
            End Using
        End Using
        Return sbRet.ToString()
    End Using

End Function

Remarks

This utility function can be useful if you want to make unit tests for your code generation application without having to persist the generated code to a file and check it that way.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here