Skip to content

Instantly share code, notes, and snippets.

@xoofx
Created September 8, 2015 14:45
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xoofx/1e81029107a34141809b to your computer and use it in GitHub Desktop.
Save xoofx/1e81029107a34141809b to your computer and use it in GitHub Desktop.
Simple CodeDom vs Roslyn syntax comparison
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