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…

MVVM - Binding Multiple Radio Buttons To a single Enum Property in WPF

I had a property in my View Model, of an Enum type, and wanted to bind multiple radio buttons to this.

Firstly, I wrote a simple Enum to Bool converter, like this.

public class EnumToBoolConverter : IValueConverter { #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (parameter.Equals(value)) return true; else return false; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return parameter; } #endregion }

And my enumeration is like

public enum CompanyTypes { Type1Comp, Type2Comp, Type3Comp } Now, in my XAML, I provided the enumeration as the ConverterParameter, of the Converter we wrote earlier, like
<Wi…