Using The Roslyn C# Compiler

Introduction

Today we will look at the Roslyn C# compiler and how to run it directly. We are so used to IDE environments that we rarely step back to think about what happens under the hood. When we compile a C# program in Visual Studio, it calls the C# compiler also known as Roslyn. Today we will write an application that targets .NET framework 5.0 and directly compile it using Roslyn and then run it from the command prompt. Hence, no Visual Studio today. So, let us begin.

Creating the Files

We are going to create a simple .NET 5 console application that prints the current time on the console. Create a folder for your files and add the below files.

DisplayText.cs

using System;
namespace AppRoslyn {
    public static class PrintOnConsole {
        public static void Show(string text) {
            Console.WriteLine(text);
        }
    }
}

Program.cs (Starting point of the application)

AppRoslyn.PrintOnConsole.Show($"Hello Word at {System.DateTime.Now.ToLongTimeString()}");

AppRoslyn.runtimeconfig.json

{
    "runtimeOptions": {
        "tfm": "net5.0",
        "framework": {
            "name": "Microsoft.NETCore.App",
            "version": "5.0.0-rc.1.20451.14"
        }
    }
}

We now have the required files. To compile these open the Developer Command Prompt and execute the following command,

dotnet "C:\Program Files\dotnet\sdk\5.0.100-rc.1.20452.10\Roslyn\bincore\csc.dll" -r:"C:\Program Files\dotnet\shared\Microsoft.NETCore.App\5.0.0-rc.1.20451.14\System.Private.CoreLib.dll" -r:"C:\Program Files\dotnet\shared\Microsoft.NETCore.App\5.0.0-rc.1.20451.14\System.Console.dll" -r:"C:\Program Files\dotnet\shared\Microsoft.NETCore.App\5.0.0-rc.1.20451.14\System.Runtime.dll" *.cs -out:AppRoslyn.dll

Here we see that we are compiling our C# files using the Roslyn compiler in the .NET 5 folder. We add the references and specify the output file name which is “AppRoslyn.dll” in this case.

We can now run the application as below,

Using The Roslyn C# Compiler

Summary

In this article, we looked at creating a console application and running it directly using the C# compiler Roslyn without the use of Visual Studio or another IDE. This might not be a normal practice in our everyday work, but it is always good to understand how things work under the hood. Happy coding!


Similar Articles