35

The post is specific to C# 8. Let's assume I want to have this method:

public static TValue Get<TKey, TValue>(
  this Dictionary<TKey, TValue> src, 
  TKey key, 
  TValue @default
) 
=> src.TryGetValue(key, out var value) ? value : @default;

If my .csproj looks like this (i.e. C# 8 and nullable types are enabled, all warnings are errors):

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <LangVersion>8</LangVersion>
    <Nullable>enable</Nullable>
    <WarningsAsErrors>true</WarningsAsErrors>
  </PropertyGroup>
  …
</Project>

This code will produce the following build-time error:

DictionaryEx.cs(28, 78): [CS8714] The type 'TKey' cannot be used as type parameter 'TKey' in the generic type or method 'Dictionary'. Nullability of type argument 'TKey' doesn't match 'notnull' constraint.

Is there any way to specify that TKey has to be a non-nullable type?

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
Alex Yakunin
  • 6,330
  • 3
  • 33
  • 52

1 Answers1

56

Ok, just found out that you can use notnull constraint:

public static TValue Get<TKey, TValue>(
    this Dictionary<TKey, TValue> src, 
    TKey key, TValue @default)
    where TKey : notnull
    => src.TryGetValue(key, out var value) ? value : @default;
Alex Yakunin
  • 6,330
  • 3
  • 33
  • 52
  • 1
    This gives an IntelliSense error "cannot resolve symbol" in VS 16.2.3, but it _does_ compile and work anyway. – V0ldek Sep 03 '19 at 09:57
  • I couldn't find any documentation on this. Do we know if this is future-proof? – NetherGranite Sep 27 '19 at 06:03
  • 6
    @NetherGranite: A year later, at least, this is now documented as part of Microsoft's [Generic Type Constraint](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-generic-type-constraint) documentation in the Language Reference, as well as the [Constraints on Type Parameters](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters#notnull-constraint) in the Programming Guide. – Jeremy Caney Apr 24 '20 at 20:13