C#C
C#7mo ago
Core

✅ Field is not initialized by the source generator: System.NullReferenceException

Hello,
I have a source generator that should initialize a field with an empty value.
The source generator is in UaDetector.SourceGenerator, and it's used byUaDetector.The generation succeeds when UaDetector project is build.
When running a project that uses UaDetector, a NullReferenceException is thrown.

Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.


The source generator initializes any field that uses the Regexes attribute. (currently with an empty list).
c#
namespace UaDetector.Parsers;

public sealed partial class BrowserParser : IBrowserParser
{
    [Regexes("Regexes.Resources.Browsers.browsers.json")]
    internal static readonly IReadOnlyList<Browser> Browsers;
}


The following code is generated:
c#
using System.Collections.Frozen;

namespace UaDetector.Parsers;

public partial class BrowserParser
{
    static BrowserParser()
    {
        Browsers = new global::UaDetector.Regexes.Models.Browsers.Browser[] { };
    }
}


UaDetector references the surce generator the following way:
<ProjectReference Include="..\UaDetector.SourceGenerator\UaDetector.SourceGenerator.csproj"
                  OutputItemType="Analyzer"
                  ReferenceOutputAssembly="false" />
Was this page helpful?