1

I'm converting code in preparation to C#9, in particular the below class implementing IGrouping<TKey, TElement>:

public class Grouping<TKey, TElement> : IGrouping<TKey, TElement>
{
    public TKey Key { get; }

    public Grouping(TKey key, IEnumerable<TElement> elements)
    {
        Key = key;
        _elements = elements;
    }
    private readonly IEnumerable<TElement> _elements;

    ...
}

Lookups support null keys so in theory the constructor should be: public Grouping(TKey? key, IEnumerable<TElement> elements)

but then Key = key; raises a warning since Key is not defined as TKey? (as per the interface's specs).

I feel like something missing in the interface's definition but maybe am I missing something?

vc 74
  • 37,131
  • 7
  • 73
  • 89
  • `GroupBy` method ignores `null` keys by default, what is the usage of your `Grouping` implementation and why do you need a `null` value as `Key`? – Pavel Anikhouski Nov 08 '20 at 15:55
  • @PavelAnikhouski `GroupBy` and the underlying `ILookup` implementation support null keys (Fiddle: https://dotnetfiddle.net/nt2xde). The reason I created my own implementation is because I need a mutable lookup. – vc 74 Nov 08 '20 at 16:08
  • According to [sources](https://source.dot.net/#System.Linq/System/Linq/Lookup.cs,87) it depends, how lookup is being used. `null` keys are omitted for joins at least. You can use the source reference to get some ideas. Null reference warning can be omitted by using a null-forgiving operator `!`. Also, I'm 100% sure, that `System.Linq` was nullable annotated already – Pavel Anikhouski Nov 08 '20 at 16:18
  • And how it will compile if you define parameter as `TKey? key`? Or that's some new feature of C# 9? – Evk Nov 08 '20 at 16:20
  • @PavelAnikhouski I agree, `IDictionary` looks annotated but maybe Linq wasn't updated. – vc 74 Nov 08 '20 at 16:26
  • @Evk Sorry, not sure I understand your question. I've enabled nullable reference types which were introduced in C#8 for my project. – vc 74 Nov 08 '20 at 16:27
  • Sure, but for me it complains (compiler error) that nullable generic type should be known as either class or struct (so either `where TKey: class OR where TKey: struct should be present in generic declaration). – Evk Nov 08 '20 at 16:31
  • Which C# version are you on? – vc 74 Nov 08 '20 at 18:42
  • @PavelAnikhouski .net5 is now in GA and `TKey` is still not nullable. I guess I have no other choice than removing warnings locally. The forgiving operator is not helpful here since I don't want to tell the compiler "I know this value is not null", but rather "the property defined in the interface is supposed to be not null but it can actually be". – vc 74 Nov 11 '20 at 16:31

0 Answers0