Step by step guide on how to debug a C# SourceGenerator in Visual Studio 2022
Valid as of 1st March 2022 with Visual Studio 2022 Version 17.1.0.
Source: [Github | Roslyn SDK | Support source generator debugging in the new Launch Profiles UI
The .NET Compiler Platform SDK must be installed.
Edit the SourceGenerator project and replace all with:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<Nullable>enable</Nullable>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
<CompilerGeneratedFilesOutputPath>Generated</CompilerGeneratedFilesOutputPath>
<IsRoslynComponent>true</IsRoslynComponent>
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.1.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.3" PrivateAssets="all" />
</ItemGroup>
<ItemGroup>
<None Include="$(OutputPath)\$(AssemblyName).dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
</ItemGroup>
4. Save it.
5. Add a Console Application project with some examples of code you would like to test the SourceGenerator with.
6. Edit the Console Application porject and add a reference to the SourceGenerator this way:
```xml
<ItemGroup>
<ProjectReference
Include="..\MySourceGenerator\MySourceGenerator.csproj"
OutputItemType="Analyzer"
ReferenceOutputAssembly="false"/>
</ItemGroup>
Properties
.Debug
.Open debug launch profiles UI
.Delete
to delete the profile shown.Add
Roslyn component
.Target project
select the Console Application project.Play
button, select your SourceGenerator project.Play
.Every time you change your source generator code, you will need to restart Visual Studio, otherwise Rebuilding the target project will not use the new version. This has something to do with Visual Studio caching.
Sources: