I created a null guard using the c# 8 "Nullable Reference Types" feature .
I placed it in a Common assembly, and call it from the App assembly. Both assemblies have <Nullable>enable</Nullable>.
My .editorconfig has dotnet_diagnostic.CA1062.severity = warning.
In the Common assembly, Common/Guard.cs:
using System;
using System.Diagnostics.CodeAnalysis;
namespace Common {
  public static class Guard {
    public static void IsNotNull([NotNull] object? arg, string? argName) =>
      _ = arg ?? throw new ArgumentNullException(argName);
  }
}
In the app assembly, App/Printer.cs:
using System;
using Common;
namespace App {
  public class Printer {
    public void PrintUpper(string text) {
      Guard.IsNotNull(text, nameof(text));
      Console.WriteLine(text.ToUpper());   // <--- CA1062
    }
    // it works when inside the same assembly:
    //public static void IsNotNull([NotNull] object? arg, string? argName) =>
    //  _ = arg ?? throw new ArgumentNullException(argName);
  }
}
Despite the null check and the [NotNull] annotation, I still get the CA1062 warning. Interestingly, the warning disappears if I move the function into the same assembly.
I thought the NRT feature works across assemblies. What am I doing / understanding wrong?
Turns out this is a bug, in roslyn's support for editorconfig.
My editorconfig had this:
dotnet_diagnostic.CA1062.severity = warning
So actually it's not a c# NRT problem.
The workaround is:
using System;
using System.Diagnostics.CodeAnalysis;
[AttributeUsage(AttributeTargets.Parameter)]
internal sealed class ValidatedNotNullAttribute : Attribute { }
namespace Common {
  public static class Guard {
    public static void IsNotNull([ValidatedNotNull][NotNull] object? arg, string? argName) =>
      _ = arg ?? throw new ArgumentNullException(argName);
  }
}
And in .editorconfig:
dotnet_diagnostic.CA1062.severity = warning
dotnet_code_quality.CA1062.null_check_validation_methods = Guard.IsNotNull
I assume once the bug is resolved, I can remove all that and it would "just work" due to NRT.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With