C
C#2y ago
no >> body

❔ Incremental Generator compilation error

I'm trying to figure out what is wrong with my helloworld generator. Here is my super simple generator, that adds a generated attribute to the source.
using Microsoft.CodeAnalysis.Text;

namespace HelloGeneratorSourceGenerator;

[Generator]
public class Generator : IIncrementalGenerator
{
public const string Attribute = @"
namespace HelloGeneratorSourceGenerator.Attributes
{
[System.AttributeUsage(System.AttributeTargets.Enum)]
public class EnumCollectionAttribute : System.Attribute
{
}
}";

public void Initialize(IncrementalGeneratorInitializationContext context)
{
context.RegisterPostInitializationOutput(
ctx => ctx.AddSource("EnumCollectionAttribute.g.cs", SourceText.From(Attribute, Encoding.UTF8)));
}
}
using Microsoft.CodeAnalysis.Text;

namespace HelloGeneratorSourceGenerator;

[Generator]
public class Generator : IIncrementalGenerator
{
public const string Attribute = @"
namespace HelloGeneratorSourceGenerator.Attributes
{
[System.AttributeUsage(System.AttributeTargets.Enum)]
public class EnumCollectionAttribute : System.Attribute
{
}
}";

public void Initialize(IncrementalGeneratorInitializationContext context)
{
context.RegisterPostInitializationOutput(
ctx => ctx.AddSource("EnumCollectionAttribute.g.cs", SourceText.From(Attribute, Encoding.UTF8)));
}
}
And after adding it I just can use them in my main project like that
using HelloGeneratorSourceGenerator.Attributes;

namespace HelloGeneratorConsole.Entities.Enums;

[EnumCollection]
public enum Foo
{
One = 0,
Two = 3
}
using HelloGeneratorSourceGenerator.Attributes;

namespace HelloGeneratorConsole.Entities.Enums;

[EnumCollection]
public enum Foo
{
One = 0,
Two = 3
}
The problem is that now I have a compilation errors and since this is my first attempt to use generators, I have no clue what I did wrong. Any ideas?
6 Replies
ero
ero2y ago
#roslyn
Thinker
Thinker2y ago
Does it build when doing dotnet build?
no >> body
no >> bodyOP2y ago
I found the reason already 😅 This is because I used in my source generator project .netstandard 2.1 After changing it to 2.0 everything works perfectly But when I use .netstandard2.1 it fails only when doing dotnet build. The project in IDE looks good, no errors and all generated types are accessible
Thinker
Thinker2y ago
ah, yeah, that'd do it Generators have to target 2.0
jcotton42
jcotton422y ago
CoreCLR Visual Studio when
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server