Skip to main content

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

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.

Popular posts from this blog

Top 7 Coding Standards & Guideline Documents For C#/.NET Developers

Some time back, I collated a list of 7 Must Read, Free EBooks for .NET Developers, and a lot of people found it useful. So, I thought about putting together a list of Coding Standard guidelines/checklists for .NET /C# developers as well.As you may already know, it is easy to come up with a document - the key is in implementing these standards in your organization, through methods like internal trainings, Peer Reviews, Check in policies, Automated code review tools etc. You can have a look at FxCop and/or StyleCop for automating the review process to some extent, and can customize the rules based on your requirements.Anyway, here is a list of some good Coding Standard Documents. They are useful not just from a review perspective - going through these documents can definitely help you and me to iron out few hidden glitches we might have in the programming portion of our brain. So, here we go, the listing is not in any specific order.1 – IDesign C# Coding StandardsIDesign C# coding stand…

Creating a quick Todo listing app on Windows using IIS7, Node.js and Mongodb

As I mentioned in my last post, more and more organizations are leaning towards Web Oriented Architecture (WOA) which are highly scalable. If you were exploring cool, scalable options to build highly performing web applications, you know what Node.js is for.After following the recent post from Scott Hanselman, I was up and running quickly with Node.js. In this post, I’ll explain step by step how I’ve setup Node.js and Mongodb to create a simple Todo listing application.Setting up Node.jsThis is what I’ve done.1 – Goto http://nodejs.org/, scroll down and download node.exe for Windows, and place it in your c:\node folder2 – Goto IIS Node project in Git at https://github.com/tjanczuk/iisnode, download the correct ‘retail’ link of IIS Node zip file (I downloaded the already built retail package, otherwise you can download and build from the source).3 – Extract the zip file some where, and run the install.bat or install_iisexpress.bat depending on your IIS Version. If you don’t have IIS in…

5 Awesome Learning Resources For Programmers (To help you and your kids to grow the geek neurons)

Happy New Year, this is my first post in 2012. I’ll be sharing few awesome learning resources I’ve bookmarked, and will be pointing out some specific computer/programming related courses I've found interesting from these resources.Also, thought about saving this blog post for my kids as well - instead of investing in these Child education schemes (though they are too small as of today, 2 years and 60 days respectively ). Anyway, personally my new year resolution is to see as much videos from this course collections (assuming I can find some free time in between my regular job && changing my babies diapers).1 – Khan AcademyAs I mentioned some time back, you and your kids are missing some thing huge if you havn’t heard about Khan Academy.  It is an awesome learning resource, especially if you want to re-visit your basics in Math, Science etc.With a library of over 2,600 videos covering everything from arithmetic to physics, finance, and history and 268 practice exercises, th…