6

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>
Khan
  • 185
  • 2
  • 10
  • Everything compiles for me. Can you add some more information? Does the library itself fails to compile? – Guru Stron May 03 '20 at 11:58
  • The library compiles when I remove the attribute. Just added some more details to the question. – Khan May 03 '20 at 12:18
  • @GuruStron did you have to install any nuget packages separately? Do you have the `nullable` context enabled for the project (not sure if this makes a difference though)? – Khan May 03 '20 at 12:22

1 Answers1

12

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

  • .NET 5.0, 6.0 Preview 6
  • .NET Core 3.1 3.0
  • .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 runtime), cause AFAIK compiler quite often relies on naming and/or duck typing.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • I didn't realise it had to be `netstardard2.1`. I added a custom one with the same name and it works fine now. Thanks – Khan May 03 '20 at 13:16