Created
September 8, 2015 14:45
-
-
Save xoofx/1e81029107a34141809b to your computer and use it in GitHub Desktop.
Simple CodeDom vs Roslyn syntax comparison
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.CodeDom; | |
using System.CodeDom.Compiler; | |
using System.IO; | |
using System.Text; | |
using Microsoft.CodeAnalysis; | |
using Microsoft.CodeAnalysis.CSharp; | |
using Microsoft.CodeAnalysis.Formatting; | |
using NUnit.Framework; | |
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; | |
namespace CodeGen.Tests | |
{ | |
public class TestCodeGen | |
{ | |
[Test] | |
public void TestCodeDom() | |
{ | |
var c = new CodeTypeDeclaration("MyType") | |
{ | |
Attributes = MemberAttributes.Public, | |
IsPartial = true, IsStruct = true, | |
Members = | |
{ | |
new CodeMemberField(new CodeTypeReference(typeof(int)), "Test") {InitExpression = new CodePrimitiveExpression(1)} | |
} | |
}; | |
var ns = new CodeNamespace("MyProject.MyNameSpace") { Types = {c} }; | |
var cu = new CodeCompileUnit() {Namespaces = {ns}}; | |
var provider = CodeDomProvider.CreateProvider("CSharp"); | |
var sb = new StringBuilder(); | |
using (var sourceWriter = new StringWriter(sb)) | |
{ | |
provider.GenerateCodeFromCompileUnit(cu, sourceWriter, new CodeGeneratorOptions()); | |
} | |
var text = sb.ToString(); | |
Console.WriteLine(text); | |
} | |
[Test] | |
public void TestRoslyn() | |
{ | |
var c = StructDeclaration("MyType") | |
.AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.PartialKeyword)) | |
.AddMembers( | |
FieldDeclaration(VariableDeclaration(PredefinedType(Token(SyntaxKind.IntKeyword)), | |
SeparatedList(new [] { VariableDeclarator("Test").WithInitializer(EqualsValueClause(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1)))) })))); | |
var ns = NamespaceDeclaration(IdentifierName("MyProject.MyNameSpace")) | |
.AddMembers(c); | |
var cu = CompilationUnit() | |
.AddMembers(ns); | |
var formattedNode = Formatter.Format(cu, new AdhocWorkspace()); | |
var sb = new StringBuilder(); | |
using (var writer = new StringWriter(sb)) | |
{ | |
formattedNode.WriteTo(writer); | |
} | |
var text = sb.ToString(); | |
Console.WriteLine(text); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment