allow using ?. on certain expressions returning a ref struct #2985
Unanswered
YairHalberstadt
asked this question in
Language Ideas
Replies: 1 comment
-
I actually came across this whilst working on the specification for #2883. At first sight, I find the idea of |
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
Uh oh!
There was an error while loading. Please reload this page.
-
Currently an expression such as
myString?.AsSpan() ?? throw new ArgumentNullException()
are illegal. This is because the specification definesmyString?.AsSpan()
as returning aNullable<ReadOnlySpan<Char>>
, and ref structs cannot be used as type parameters.This is over-limiting for a couple of reasons:
a)
There's really no reason not to allow a nullable ref struct. Ideally we would like to be able to express conditional ref structness - i.e.
Nullable<T>
is a ref struct if and only ifT
is a ref struct.Whilst I don't think it's worth adding this construct to the type system, the language and runtime might be able to specialise
Nullable<T>
.b)
In many cases the compiler optimises away the temporary nullable anyway, even in debug. For example
int M(string s) => s?.Length ?? 0;
becomes:Which is equivalent to:
It would be nice if we could formalize this in the specification, and thus allow ref structs to be part of such ?. expressions.
Here is an attempt at doing so:
Given an expression of form:
subexpression1?.subexpression2 ?? subexpression3
where subExpressions can be any expression.
This is equivalent to:
(subExpression1 is {} temp) ? temp.subexpression2 : subexpression3
Beta Was this translation helpful? Give feedback.
All reactions