I am experimenting with C# source generators. I have spent about a day on it, and I find it a very frustrating and painful experience. IntelliSense is extremely unreliable. It occasionally works, but most often it does not, and I have not been able to figure out any system to it. (Restarting Visual Studio does not help.)
But more fundamentally, I have great trouble debugging errors in the generated code. When I make a mistake in the template in the source generator and try to compile, I might get errors like "Method must have a return type" in the generated file. But when I double-click on the error, it doesn't take me to the generated code. That makes it extremely hard to see what is wrong with it.
Is there a trick to it? Is there any way to inspect the generated code when it fails to compile? And more generally, what governs when the generated code is available for IntelliSense and when it is not?
I am using Visual Studio Professional 2022 version 17.1.6 and ReSharper 2022.1.
Thanks in advance!
I have found a partial solution to my problem.
First, do not use the ReSharper builder in Visual Studio when working with source generators. It does not give proper error messages. Instead, run dotnet build
from a command line. You'll get much better error messages that way.
In fact, part of my problem may be due to bugs or limitations in ReSharper (though I have not investigated this, so that is pure speculation).
Second, you can test the innards of your source generator without running the source generation at compile time.
OutputItemType="Analyzer"
in your project reference.Moreover, as NightOwl888 pointed out, I can add this to the referencing project in order to get it to spit out the generated files to disk ( as explained in this article):
<PropertyGroup>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
</PropertyGroup>
I have not solved the IntelliSense problem, but now I can at least endure working with this generator.