Search code examples
c#nullability

How to resolve error 'NotNullWhen attribute is inaccessible due to its protection level'


I have the following extension method and I'm trying to decorate the out parameter (T value) with the NotNullWhen attribute. However, it displays the error 'NotNullWhen attribute is inaccessible due to its protection level' that I can't figure out why?

    using System;
    using System.Collections.Generic;
    using System.Diagnostics.CodeAnalysis;

    internal static class Extensions
    {
        public static bool TryGetValueForAssignableType<T>(this IDictionary<Type, T> dictionary, Type key, [NotNullWhen(true)] out T value)
        {
            value = default;

            foreach (var pair in dictionary)
            {
                if (pair.Key.IsAssignableFrom(key))
                {
                    value = pair.Value;
                    return true;
                }
            }

            return false;
        }
    }

I've tried changing the class access modifier to public with no effect. I also have C# 8 nullable context enabled for the class library.

Any idea how to resolve this?

Edit:

I just tried creating a new class library with just the extensions class above. Now it displays 'The type of namespace name 'NotNullWhen' could not be found (are you missing a using directive or an assembly reference)'. I've already included using System.Diagnostics.CodeAnalysis; which is greyed out though. The project file contains the following:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <Nullable>enable</Nullable>
    <LangVersion>8.0</LangVersion>
  </PropertyGroup>

</Project>

Solution

  • If your open documentation you will see that NotNullWhenAttribute applies to:

    • .NET Core 3.0, Core 3.1, 5, 6, 7, 8
    • .NET Standard 2.1

    TBH I failed to build lib against .NET Standard 2.1 also, but you try can either install nuget like this one or implement this attribute yourself (like it is done in the runtime), cause AFAIK compiler quite often relies on naming and/or duck typing.