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!
Add the following to your code generator constructor code:
#if DEBUG
if (!Debugger.IsAttached)
{
Debugger.Launch();
}
#endif
Now you can use breakpoints in Visual Studio.
Intellisense is indeed garbage in VS with code generators. You need to close VS, delete /bin and /obj folders, reopen VS, then rebuild. This has to be done everytime you make changes. VS will show the old version after you changed something, intellisense will mark new things as error, yet it will still compile and run...
For a better experience I recommend using Rider, which has a much better integration experience for code generators.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With