Returning default(T?) shows null warning even though T is nullable #1611
-
Was just playing around on SharpLab and found this: public static T? Foo<T>() => default; // Cannot convert null literal to non-nullable reference
public static string? Bar() => default; // Perfectly fine This seems counter intuitive to me. Maybe I'm not understanding this right. Both I saying I would expect that if I passed either But if it is the latter, why is it there no warning for Also |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments
-
It would be
There's no such thing as |
Beta Was this translation helpful? Give feedback.
-
Try to use T as structure: public static T? Foo() where T:struct => default(T?); |
Beta Was this translation helpful? Give feedback.
-
@stakx I know there isn't, that's why I said:
If I did that though, wouldn't I not be able to use |
Beta Was this translation helpful? Give feedback.
-
unfortunately, "string?" is not available in the current version. It is gonna be included in C# 8 |
Beta Was this translation helpful? Give feedback.
It would be
int
.There's no such thing as
int??
. UsingT?
requires you to add a generic parameter type constraintwhere T : struct
to your method, becauseNullable<T>
likewise constraintsT
to bestruct
and that constraint is "propagated" to your method. It appears that awhere T : struct
explicitly disallowsT
to be a nullable value type (my guess is to prevent nested or multiply-nullable types), so once you add the constraint, you'll no longer be able to use e.g.int?
as a generic type argument.