Compiling C# 6.0 Code Using Roslyn Microsoft.CodeAnalysis v1.0.0

Since the recent release of Roslyn aka Microsoft.CodeAnlysis most of the articles and blogs on the Internet that were written using Alpha or Beta versions of Roslyn are now outdated.

Recently I wanted to write a program using the latest stable version (v1.0.0) of Roslyn to compile the C# 6.0 version code using .NET 4.6 framework. In old beta versions, there was no option for specifying Target framework and compiler Run Time or maybe I missed it somehow. I was interested in learning how to achieve the same in the  latest release. I tried searching the Internet and other websites like Stackoverflow but all I got was end up landing on content that was written using older versions.

I finally got it working and sharing the same with code sample.

Roslyn Version

Microsoft.CodeAnalysis version="1.0.0"

Install it from Nuget:

Install-Package Microsoft.CodeAnalysis -Version 1.0.0

Sharing my initial observations of this encounter:
  1. Roslyn have become more extensible.

  2. Less dependency on the platform version on Roslyn based utilities.

  3. The problem was with one package “Microsoft.Workspaces.Desktop” which failed by build because this library requires 4.5.2 or latest .NET version 4.6. So I had to install 4.6 to make it working.

  4. Now you can specify almost everything required for customized compilation.

Here’s my complete program. This is a console application that compiles a csharp file to a DLL. The latest functions in Roslyn have options to supply more information e.g. which platform you want to use for Compilation and what compilation or language version you want to use.

  1. public class Program  
  2. {  
  3.     private static readonly IEnumerable<string> DefaultNamespaces =  
  4.         new[]  
  5.         {  
  6.             "System",   
  7.             "System.IO",   
  8.             "System.Net",   
  9.             "System.Linq",   
  10.             "System.Text",   
  11.             "System.Text.RegularExpressions",   
  12.             "System.Collections.Generic"  
  13.         };  
  14.   
  15.     private static string runtimePath = @"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6\{0}.dll";  
  16.   
  17.     private static readonly IEnumerable<MetadataReference> DefaultReferences =  
  18.         new[]  
  19.         {  
  20.             MetadataReference.CreateFromFile(string.Format(runtimePath, "mscorlib")),  
  21.             MetadataReference.CreateFromFile(string.Format(runtimePath, "System")),  
  22.             MetadataReference.CreateFromFile(string.Format(runtimePath, "System.Core"))  
  23.         };  
  24.   
  25.     private static readonly CSharpCompilationOptions DefaultCompilationOptions =  
  26.         new CSharpCompilationOptions(OutputKind.WindowsRuntimeApplication)  
  27.                 .WithOverflowChecks(true)  
  28.                 .WithOptimizationLevel(OptimizationLevel.Release)  
  29.                 .WithUsings(DefaultNamespaces);  
  30.   
  31.     public static SyntaxTree Parse(string text, string filename = "", CSharpParseOptions options = null)  
  32.     {  
  33.         var stringText = SourceText.From(text, Encoding.UTF8);  
  34.         return SyntaxFactory.ParseSyntaxTree(stringText, options, filename);  
  35.     }  
  36.   
  37.     public static void Main(string[] args)  
  38.     {  
  39.         var fileToCompile = @"C:\Users\....\Documents\Visual Studio 2013\Projects\ConsoleForEverything\SignalR_Everything\Program.cs";  
  40.         var source = File.ReadAllText(fileToCompile);  
  41.         var parsedSyntaxTree = Parse(source, "", CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6));  
  42.   
  43.         var compilation  
  44.             = CSharpCompilation.Create("Test.dll"new SyntaxTree[] { parsedSyntaxTree }, DefaultReferences, DefaultCompilationOptions);  
  45.         try  
  46.         {  
  47.             var result = compilation.Emit(@"c:\temp\Test.dll");  
  48.   
  49.             Console.WriteLine(result.Success ? "Sucess!!" : "Failed");  
  50.         }  
  51.         catch (Exception ex)  
  52.         {  
  53.             Console.WriteLine(ex);  
  54.         }  
  55.         Console.Read();  
  56.     }  
  57. }  
Although it’s not well organized but this will give you a kick start.

The new Code Analyzer and C# syntax rewriters are more interesting things and are on my list to explore.

 


Similar Articles