1

Assuming C# 8.0 and reference type nullability, why are these signatures considered equal:

void Test<T>(IEnumerable<T> enumerable) where T : class
void Test<T>(IEnumerable<T> enumerable) where T : struct

but these are not?

void Test<T>(IEnumerable<T?> enumerable) where T : class
void Test<T>(IEnumerable<T?> enumerable) where T : struct

The only thing different is the nullability of enumerable elements.

Krzaku
  • 186
  • 4
  • 16
  • Err... Struct are considered value types, and by definition can't be null right? – Milney Feb 07 '20 at 14:20
  • 1
    I assume this is C# 8? – DavidG Feb 07 '20 at 14:21
  • Type constraints aren't used for overload resolution. They are checked *after* overload resolution. I think this is a duplicate of [Overload resolution issue for generic method with constraints](https://stackoverflow.com/questions/26037469/overload-resolution-issue-for-generic-method-with-constraints) –  Feb 07 '20 at 14:25
  • 4
    `T?` when `T` is a `struct` is `Nullable`, which is distinguishable from any class `T`. (Note that this works whether you use `T` or `T?`, NRTs aren't strictly relevant in this case and of course `T` and `T?` with `T` a `class` are "the same" type from a runtime perspective.) For the `T` case it's the well-known problem that [constraints aren't used in overload resolution](https://stackoverflow.com/q/26037469/4137916). – Jeroen Mostert Feb 07 '20 at 14:26
  • @JeroenMostert thank you, that does actually make sense. If you want you can put that comment up as answer and I'll chose it. – Krzaku Feb 07 '20 at 14:28
  • 2
    @Any Don't think that's a good dupe target. Note the code presented here works differently in C#8 vs C#7. – DavidG Feb 07 '20 at 14:31
  • @DavidG Okay, sorry about that. I misinterpreted OPs comment. I thought they were referring to the dupe target when they said "that does make sense, if you put that up, I'll accept it and close". My bad. I *really* dislike being able to unilaterally close questions. –  Feb 07 '20 at 14:37
  • @Amy Hey, it's all fine, I don't mind the hammer, we just have to be careful when using it. I get it wrong too. – DavidG Feb 07 '20 at 14:52

0 Answers0