Home > database >  Nullability warning for a field instatiated in Setup, BenchmarkDotNet
Nullability warning for a field instatiated in Setup, BenchmarkDotNet

Time:07-19

The field _requestSigner2 is giving the nullability warning. It's basically instatiated in Setup(), which is the normal routine in BenchmarkDotNet but Visual Studio doesn't know that. What is the recommended way to solve that? = null!?

[MemoryDiagnoser]
public class RequestSignerBenchmarks
{
    private RequestSigner2 _requestSigner2;

    [GlobalSetup]
    public void Setup()
    {
        _requestSigner2 = RequestSigner2.FromSecret("aGlkZGVu");
    }

    [GlobalCleanup]
    public void Cleanup()
    {
        _requestSigner2.Dispose();
    }

    [Benchmark]
    public void First()
    {
        var timestamp = TimestampProvider.Default.CurrentTimestamp();
        _requestSigner2.Sign(timestamp, "GET", "products", "");
    }

    [Benchmark]
    public void Second()
    {
        var signer = RequestSigner.FromSecret("aGlkZGVu");

        var timestamp = TimestampProvider.Default.CurrentTimestamp();
        signer.Sign(timestamp, "GET", "products", "");
    }
}

CodePudding user response:

Personally I would just create a static field in this case (since you don't have complex/parameter depended initialization logic):

public class RequestSignerBenchmarks
{
    private static RequestSigner2 _requestSigner2 = RequestSigner2.FromSecret("aGlkZGVu");
    // ...
}

CodePudding user response:

Using = null! is indeed a good way to deal with this warning. But I suggest you have all benchmarks separated or identified somehow to disable them in rules using pattern matching.

Example:

[*.bench.cs] or [*/Benchmarks/*.cs]

./.editorconfig

[*/Benchmarks/*.bench.cs]

# CS8618: Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
dotnet_diagnostic.CS8618.severity = none
  • Related