2

Is this possible to generate code with Source Generator in c# into class library project? I would like this auto-generated code to be packed into Nuget package then.

When I try to build a project made according to the Microsoft(https://learn.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/source-generators-overview) tutorial I encounter the following error:

CSC : warning CS8785: Generator 'HelloSourceGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type 'NullReferenceException' with message 'Object reference not set to an instance of an object.

The only difference is that I am trying to generate code for a class library project, not a console application.

I tried to do it according to the guide posted on Microsoft's website(https://learn.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/source-generators-overview), but it assumes generating code for an application that has a console interface.

4
  • 3
    That sounds like your generator has a bug (throws that exception). A generator can work in any type of (C#) project Commented Dec 10, 2023 at 18:44
  • @HansKesting I think my generator has no errors. I prepared two projects (one a console application, the other a class library) using the generator project in exactly the same way. The console project generates classes, while the library project does not. Commented Dec 10, 2023 at 18:56
  • 1
    @TheStix13 "The console project generates classes, while the library project does not." - this does not prove that your source generator does not have a bug. Please share a minimal reproducible example. Commented Dec 10, 2023 at 21:01
  • Solved! So, basically I was using template code without exactly knowing what is happening inside of it. Thank you @GuruStron! Your answer was very helpful. Commented Dec 11, 2023 at 1:48

2 Answers 2

4

Assuming that you have followed the docs to a tee, the following should be the issue:

// Find the main method
var mainMethod = context.Compilation.GetEntryPoint(context.CancellationToken);

As comment states this will find the main method which library project obviously does not have, so based on the sources and docs:

Returns the Main method that will serves as the entry point of the assembly, if it is executable (and not a script).

mainMethod will be null, hence the exception you see. Usually you want to analyze assembly for some syntax, for example as I do in my currently unfinished generator:

public void Initialize(GeneratorInitializationContext context)
{
    context.RegisterForSyntaxNotifications(() => new RecordSyntaxReceiver());
}

Code for receiver can be found here.

Also I highly recommend to go through the linked in the docs Source Generator Samples @github and Source Generators Cookbook.

Sign up to request clarification or add additional context in comments.

1 Comment

Another common way is to define an attribute and look for its usage, like the MVVM source generators or the AutoBindable generator do.
0

Check out this little open-source CsCodeGenerator if it helps:
https://github.com/borisdj/CsCodeGenerator

It is based on Classes and its elements: Fields, Properties, Methods,..
Has the ability to create ClassModels and write it to .cs files.

Sample for ComplexNumber class:

ClassModel complexNumberClass= new ClassModel("ComplexNumber");

var properties = new Property[]
{
    new Property(BuiltInDataType.String, "DefaultFormat")
    {
        SingleKeyWord = KeyWord.Static,
        IsGetOnly = true,
        DefaultValue = @"""a + b * i"""
    },
    new Property(BuiltInDataType.Double, "Real"),
    new Property(BuiltInDataType.Double, "Imaginary"),
    new Property(BuiltInDataType.String, "Remark")
    {
        SingleKeyWord = KeyWord.Virtual,
        IsAutoImplemented = false,
        GetterBody = "remark",
        SetterBody = "remark = value"

    },
}.ToDictionary(a => a.Name, a => a);

complexNumberClass.Properties = properties;

PS I'm the author.

2 Comments

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review
@LinDu edited with more detailed explanation. thx for suggestion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.