CSharp6Test // Creating A Tiny Roslyn app To Explore The Features Of C# 6.0

By Anoop Madhusudanan

Vote on HN

Some of the C# 6.0 Features are exciting. And you can try them out now as the new Roslyn preview is out. You can explore the language features that are completed in this list, from the Roslyn documentation in CodePlex. Some of the ‘Done’ features for C#, based on the documentation there include

  • Primary constructors   -   class Point(int x, int y) { … }  
  • Auto-property initializers -     public int X { get; set; } = x; 
  • Getter-only auto-properties  -   public int Y { get; } = y;  
  • Using static members  -   using System.Console; … Write(4);
  • Dictionary initializer  -  new JObject { ["x"] = 3, ["y"] = 7 }    
  • Indexed member initializer   -  new JObject { $x = 3, $y = 7 }    
    Indexed member access -   c.$name = c.$first + " " + c.$last;  
  • Declaration expressions -   int.TryParse(s, out var x);    
  • Await in catch/finally  -  try … catch { await … } finally { await … }   
  • Exception filters -    catch(E e) if (e.Count > 5) { … }   

In this post, we’ll explore.

  • How to parse and walk the Roslyn syntax tree and dump it
  • How to write a small ‘compiler’ using Roslyn’s CSharpCompilation
  • Use the same to explore if those features are implemented.

We could’ve used REPL/Scripting APIs, but sadly it is not available in the new version pre-release – So let us write a simple app using Roslyn APIs to test the new features in C# Winking smile

[Ouch, lazy to write the code? Fork it from Github - https://github.com/amazedsaint?tab=repositories ]

Our CSharp6Test App

Create a new C# Project in Visual Studio 2012/2013, fire up Nuget console, and install Rolsyn pre release bits. I’m doing this in VS 2012.

  Install-Package Microsoft.CodeAnalysis -Pre

Now, let us write some code to parse the Syntax tree and do the compilation


//FILE - MAIN.CS
//amazedsaint.com

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharp6Test
{

    class Program
    {
        static void Main(string[] args)
        {

            try
            {

                Console.WriteLine("C#> Roslyn Code Verifier.");
                if (args.Count() < 0)
                {
                    Console.WriteLine("C#> Usage: CSharp6Test <file>");
                    return;
                }

                //User provided the output filename
                string file = args[0];

                string output = (args.Count() > 2) ? output = args[1] : file + ".exe";

                //Create a syntax tree from the code
                SyntaxTree tree = CSharpSyntaxTree.ParseText(File.ReadAllText(file));


                Console.WriteLine("C#> Dumping Syntax Tree");
                Console.WriteLine();

                //Dumping it using our extension method
                tree.Dump();
                Console.WriteLine();

                //Compile
                Console.WriteLine("C#> Trying to compile Syntax Tree");
                tree.Compile(output);

            }
            catch (Exception ex)
            {
                Console.WriteLine("Oops: {0}", ex.Message);
                Console.WriteLine("Sorry Skywalker, that was an exception - Love, Yoda");
            }

        }
    }
}


Well, as it is evident, we are just parsing the syntax tree from the file, dumping it, and then compiling it. The Dump and Compile extension methods are here for your service.

//FILE - SYNTAXTREEEXTENSIONS.CS
//amazedsaint.com

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharp6Test
{
    public static class SyntaxTreeExtensions
    {
        public static void Dump(this SyntaxTree tree)
        {
            var writer = new ConsoleDumpWalker();
            writer.Visit(tree.GetRoot());
        }

        class ConsoleDumpWalker : SyntaxWalker
        {
            public override void Visit(SyntaxNode node)
            {
                int padding = node.Ancestors().Count();
                //To identify leaf nodes vs nodes with children
                string prepend = node.ChildNodes().Count() > 0 ? "[-]" : "[.]";
                //Get the type of the node
                string line = new String(' ', padding) + prepend +
                                        " " + node.GetType().ToString();
                //Write the line
                System.Console.WriteLine(line);
                base.Visit(node);
            }

        }

        public static void Compile(this SyntaxTree tree, string output)
        {

            //Creating a compilation
            var compilation = CSharpCompilation.Create
         ("CSharp6Test", new List<SyntaxTree> { tree })
                              .AddReferences(
          new MetadataFileReference
    (typeof(object).Assembly.Location),
                               new MetadataFileReference
    (typeof(ASCIIEncoding).Assembly.Location), 
                               new MetadataFileReference
    (typeof(IEnumerable<>).Assembly.Location), 
                               new MetadataFileReference
    (typeof(IEnumerable).Assembly.Location),  
                               new MetadataFileReference
    (typeof(Enumerable).Assembly.Location));   


            //Lets do the diagnostics
            var check = compilation.GetDiagnostics();


            //Report issues if any
            if (check.Count() > 0)
            {

                bool hasError = false;

                Console.WriteLine();
                Console.WriteLine("C#> Few Issues Found");
                foreach (var c in check)
                {
                    Console.WriteLine("{0} : {1} in {2}", c.Severity, c.GetMessage(), c.Location);
                    if (c.Severity == DiagnosticSeverity.Error) hasError = true;
                }
                if (hasError)
                {
                    Console.WriteLine("C#> Errors found. Aborting");
                }

            }

            var emit = compilation.Emit(output);

            if (emit.Success)
                Console.WriteLine("C#> No Errors Found. Created {0}", output);
            else
                Console.WriteLine("C#> Oops, can't create {0}", output);
        }


    }
}

And that is it. Go ahead and compile as you please. You've a tiny tool to test the new C# features. Checkout my next post about experimenting with some of the C# 6.0 features.
© 2012. All Rights Reserved. Amazedsaint.com