Start your first source generator
Init your source generator project
Create a new classlib project for source generator
bash
dotnet new classlib -n MySourceGenerator
1
Add dependencies
bash
dotnet add package Microsoft.CodeAnalysis.Analyzers && dotnet add package Microsoft.CodeAnalysis.CSharp
1
Configure .csproj
property
- Set
TargetFramework
asnetstandard2.0
, it's required, not an option.
Additionally, set the
LangVersion
as your need, or it will target toC# 7.3
by default.
xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netstandard2.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>latest</LangVersion>
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
</PropertyGroup>
</Project>
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
Init your console project for testing your generator
Create a new console project
bash
dotnet new console -n WorkWithSourceGenerator
1
Reference source generator project in console project
Edit your .csproj
in console project as following.
xml
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="../MySourceGenerator/MySourceGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup>
</Project>
1
2
3
4
5
6
7
2
3
4
5
6
7
TIP
In this case, two projects are placed in a same folder.
Create a new generator
Create a new file in generator project, implement IIncrementalGenerator
for your generator.
cs
using Microsoft.CodeAnalysis;
namespace MySourceGenerator;
[Generator]
public class HelloSourceGenerator : IIncrementalGenerator
{
public void Initialize(IncrementalGeneratorInitializationContext context)
{
throw new NotImplementedException();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
WARNING
ISourceGenerator
should be deprecated since .NET6
, why is that? Check out this: Source generator updates: incremental generators