Introduction
With C# 9 we got introduced to Source Generators which are really awesome and have potential for many things. In this post I will describe how I ended up debuging them as I was creating my ViewBindingsGenerator project for Android apps.
The Problem
Visual Studio 2019 & Visual Studio 2022 are really great for development but source generators is one place where they fall short.
There are many great articles out there but none help with the actual problem of debuging your generator as a novice without tests or the knowledge to write some. Also not knowing what you are looking for adds to the burden and in the end you just want to play with your code just like in the SourceGeneratorPlayground but more involved.
After fighting the tooling and trying to debug my code, where at that point I was still exploring plus I didn't know a lot of things so it became a problem.
The Solution
As I was about to give up It hit me, I just in the end want to at least see some text somewhere like in the console (the Javascript way xD). So using VS Code, it's built in console and this code
#if DEBUG
internal static class Log
{
public static List<string> Logs { get; } = new();
public static void Print(string msg) => Logs.Add("//\t" + msg);
// More print methods ...
public static void FlushLogs(GeneratorExecutionContext context)
{
context.AddSource($"logs.g.cs", SourceText.From(string.Join("\n", Logs), Encoding.UTF8));
}
}
#endif
I started debuging my code with no problems!
The code is really simple, you have several methods that will append strings in a list, each entry is a new commented line that will be printed to a C#
file.
Using the last method FlushLogs
which I call at the end of my generator context.FlushLogs()
I "printed" the messages.
The VS Code Setup:
At the bottom of the screen I am either running dotnet build
or dotnet clean && dotnet build
to get a clean generation (bonus with VS Code I never lose my open logs.g.cs
file).
To the right I have the logs.g.cs file which is located in obj/Debug/{platform}/generated
depending on your project.
To the left I have the code I am testing on which I call the Log
class and it's print methods.
The most important part for me was to keep the Log class only in the #If DEBUG
so that I could remove it later for release!
The End
And that's it, even if it is dirty, it gets the job done especially for a novice and allowes you to code a lot faster for now until the tooling gets better!
If anyone has better ways please do provide links in the comments 😁
Top comments (0)