Generator attribute
Learn source generator registration with the [Generator] attribute.
Generator attribute
The [Generator] attribute marks a class as a source generator and registers it with the compiler. Without this attribute, your class is not recognized as a generator.
The generator class must implement IIncrementalGenerator (or the older ISourceGenerator). Registration is automatic; you do not write a registration file by hand.
Attribute and interface together
A generator class carries the [Generator] attribute and implements the IIncrementalGenerator interface. The Initialize method is the entry point where the generator starts and sets up its pipeline.
In this lesson we simulate the registration by defining our own GeneratorAttribute class and applying it to a generator class. This shows you how the attribute marks the class.
Exercise Define a generator class
First define a GeneratorAttribute : Attribute class marked with [AttributeUsage(AttributeTargets.Class)]. Then write a LogGenerator class marked with [Generator]; give it a public string Name => "LogGenerator"; property. In Main, print Console.WriteLine(new LogGenerator().Name).
Show example solution
Attribute { }. Write [Generator] class LogGenerator { public string Name => "LogGenerator"; }. In Main: Console.WriteLine(new LogGenerator().Name);
Example solution:
using System;
[AttributeUsage(AttributeTargets.Class)]
class GeneratorAttribute : Attribute { }
[Generator]
class LogGenerator
{
public string Name => "LogGenerator";
}
class Program
{
static void Main()
{
Console.WriteLine(new LogGenerator().Name);
}
}
Test yourself
-
Match each registration concept
- [Generator]
- Mark class as generator
- IIncrementalGenerator
- Modern generator interface
- Initialize
- Generator entry point
-
Complete the generator class declaration
[Generator] class ____ { public string Name => "LogGenerator"; }Show answer
[Generator] class LogGenerator { public string Name => "LogGenerator"; } -
What registers a class as a source generator?
- [Generator]
- [Serializable]
- [DllImport]
- [Obsolete]
Show answer
[Generator] — Correct. The [Generator] attribute performs registration.