Basic examples using .NET Code Generators.
There are two key types of .NET code generators available, Incremental Generator and the deprecated Source Generator. As this repository grows, both examples will be provided. Focusing primarially on the preferred method. For more information, check out the Roslyn SDK.
Since these methods have a lack of clear documentation, this article references various sources found on the internet.
Author: Damian Suess
Website: SuessLabs.com
Submitted with ❤ by Xeno Innovations, Inc. and Suess Labs.
When creating a code generator, be VERY mindful of your technique. Check out, Avoiding Performance Pitfalls by Andrew Lock.
Changes to your code will put pressure on the compiler and can have a negative impact on your developer (IDE) experience. The code samples here don't always use the best techniques.
The examples provided use Avalonia and the Prism.Avalonia library for a visual cross-platform MVVM experience. Sure, a console app would quickly suffice; visuals are sometimes better.
The examples provided are crude with the intention to quickly point out how to implement.
Both Incremental and Source Generator projects perform the same actions. "Incremental" is recommended for .NET 6 and above.
Basic example for generating properties based on the attribute NotifyField used by an MVVM application (similar to CommunityToolkit's Observable attribute).
public partial class MainWindowViewModel
{
[NotifyField]
private string _firstName;
[NotifyField]
private string _lastName;
// ...
}This will generate 2 files, {CLASSNAME}_notifyable.g.cs and NotifyFieldAttribute.g.cs.
// Sample contents of: MainWindowViewModel_notifyable.g.cs
public partial class MainWindowViewModel : Prism.Mvvm.BindableBase
{
public string FirstName
{
get => this._firstName;
set
{
SetProperty(ref this._firstName, value);
//this._firstName = value;
// this.PropertyChanged?.Invoke(this, new System.ComponentModel.PropertyChangedEventArgs(nameof(FirstName)));
}
}
...How to create custom attributes and code generators
Your code generator project must be itw own project, and using netstandard2.0.
Referencing your code gen project can be done in one of two ways
<!-- Path to the DLL -->
<Analyzer Include="..\MvvmApp.Generators\bin\Debug\netstandard2.0\MvvmApp.Generators.dll"/>
<!-- Or, reference the project -->
<ProjectReference Include="..\MvvmApp.Generators\MvvmApp.Generators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />- Source Generators Samples
- Video - Using Source Generators
- Incremental Generator
- Sections of this is based on CommunityToolkit.Mvvm
ObservableProperty.