Skip to content

Instantly share code, notes, and snippets.

@andygjp
Created January 9, 2017 23:25
Show Gist options
  • Save andygjp/201201e867c3147c80f274751bb0cf00 to your computer and use it in GitHub Desktop.
Save andygjp/201201e867c3147c80f274751bb0cf00 to your computer and use it in GitHub Desktop.
Create an enumeration using Roslyn
namespace ConsoleApplication8
{
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Emit;
// nuget install Microsoft.Net.Compilers # Install C# and VB compilers
// nuget install Microsoft.CodeAnalysis # Install Language APIs and Services
class Program
{
static void Main(string[] args)
{
EnumMemberDeclarationSyntax member1 = SyntaxFactory.EnumMemberDeclaration(SyntaxFactory.Identifier("MyMember1"));
SeparatedSyntaxList<EnumMemberDeclarationSyntax> members = SyntaxFactory.SeparatedList(new[] { member1 });
SyntaxTokenList modifiers = SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword));
EnumDeclarationSyntax enumeration = SyntaxFactory.EnumDeclaration(new SyntaxList<AttributeListSyntax>(), modifiers, SyntaxFactory.Identifier("MyEnum1"), null, members);
NamespaceDeclarationSyntax @namespace = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.IdentifierName("MyNamespace1")).AddMembers(enumeration);
CompilationUnitSyntax compilationUnit = SyntaxFactory.CompilationUnit().AddMembers(@namespace);
var mscorlib = typeof(object).GetTypeInfo().Assembly;
var reference = MetadataReference.CreateFromFile(mscorlib.Location);
var compiledCode = CSharpCompilation.Create("Mine.dll",
options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
syntaxTrees: new[] {compilationUnit.SyntaxTree},
references: new[] {reference});
// Now read the code into a memory stream. You can then load types out of the assembly with reflection
Assembly assembly;
using (var stream = new MemoryStream())
{
EmitResult compileResult = compiledCode.Emit(stream);
if (!compileResult.Success)
{
throw new InvalidOperationException();
}
assembly = Assembly.Load(stream.GetBuffer());
}
var types = assembly.ExportedTypes.ToList();
Debug.Assert(types.Count > 0);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment