Generalize requirements for ??
and ?.
operators to make them usable on custom types (via .HasValue()
, .GetValueOrDefault()
detection)
#8400
Unanswered
T-Gro
asked this question in
Language Ideas
Replies: 3 comments 3 replies
-
This means that nullability will affect code generation which is an explicit no-no when nullable reference types was introduced in C#. |
Beta Was this translation helpful? Give feedback.
2 replies
-
Related? dotnet/runtime#105923 |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
The built-in null coalescing
??
and null propagation?.
operators enable succinct processing of data that is possibly absent.The operators can be composed in a longer sequence and work both on
System.Nullable<T>
type as well as nullable reference types.What is not possible at the moment is to use the two operators with custom containers representing possible absence of information.
The following examples come to mind:
Option<>
,ValueOption<>
andResult<>
typesMaybe
types popular in functional-C# codebases https://github.com/search?q=Maybe+language%3AC%23&type=codeOptional
types https://github.com/search?q=Optional%3CT%3E+language%3AC%23&type=codeThe proposal is to expand the two operators to be based on a pattern detected on the left-hand side of the expression.
The needs would be defined by having instance/extension methods accessible in current scope with the following signature:
bool HasValue()
T GetValueOrDefault()
For handling
?.
null propagation, a static property representing the "missing data" scenario is needed:$containerType<T>.None
. If one does not exist,null
is used for reference types and defaultSystem.Nullable<T>
is returned for value types.Migration concerns:
If the left-hand side is a
System.Nullable<T>
, the current rules would apply, no changes.If the left-hand side is a nullable reference type known to be maybe null or null-oblivious, , the current rules would apply, no changes (it would be handy for many of the above mentioned containers to combine a
x != null && x.HasValue()
together, but that could be a breaking change for existing code).Only if the left-hand side is a non-nullable value type or a reference type known to be not null, the detection for
HasValue()
andGetValueOrDefault()
would start.Beta Was this translation helpful? Give feedback.
All reactions