1 year ago

#317229

test-img

Frank

How to properly reference classes output by Source Generators in C#

A .NET 5 console app uses an Analyzer that includes a Source Generator to generate test cases as classes. These are output to a temporary folder like this:

 <PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
  <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
  <CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GeneratedFiles</CompilerGeneratedFilesOutputPath>
  <RunAnalyzersDuringBuild>False</RunAnalyzersDuringBuild>
  <RunAnalyzersDuringLiveAnalysis>True</RunAnalyzersDuringLiveAnalysis>

The generated classes are referenced in the main Program, instantiated, and executed:

  await TestFunction("Simple addition - uint.", new SimpleAdditionUint.SimpleAdditionUint(), ba => CheckUint(ba,3));

where the above SimpleAdditionUint.SimpleAdditionUint is generated by the Source Generator.

What I am experiencing is that if the folder with the generated files is not included in the csproj, then despite the project successfully building, there are edit-time error diagnostics warning that the classes do not exist.

If I include the output files in the csproj, then at build time I get errors that the types already exist. I would need a pre-build step to empty the included folder.

I am surprised by this behaviour and cannot find anything similar online. Is there some project setting I am missing here?

c#

csharp-source-generator

0 Answers

Your Answer

Accepted video resources