roslyn: Please add new syntax keyword "ref?" to represent that "ref return" result might be null
Now the C#7.0 feature “ref return” doesn’t allow null as return value, but null as return value is sometimes useful. For example:
static ref? int findvalue(int[] arr, int value){
int i;
for(i=0;i<arr.Length;i++){
if(value==arr[i])return ref arr[i];
}
return null; //not found
}
int[] array=new int[]{1,2,3};
ref? int e=findvalue(array, 4);
if(e!=null)e=5;
ref? int e1=finevalue(array,3);
if(e1!=null)e1=0;
..........
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Comments: 15 (8 by maintainers)
http://mustoverride.com/refs-not-ptrs/
With
ref
parameters, if I don’t care about some parameter, using a dummy local variable with a default value is probably enough and then I can just ignore it after the call.With
ref
returns, if I don’t have any variable to return, the caller probably has to be be told about it somehow (possibly using abool
flag, as you suggested) and I have to somehow allocate storage for the dummy variable on the heap (or it could be astatic
field).So I think it indeed is a bigger issue with
ref
returns than withref
parameters.@jnm2
Returning
ref int?
is probably as close as you get, short of digging into unsafe territory at which point you’d probably be better off skippingref
and diving straight into pointers.From the blog post above it sounds very much like this request to be able to work with
ref
as if it’s a “pointer-lite” was never intended. Thatref
as a modifier doesn’t change what the type is, only where it is. But given the milestone tag maybe they’re willing to reconsider it. My question would be what additional work might need to be done with the verifier to enable such scenarios, as I understand thatref
returns already ran afoul of some of the code safety enforcement features.Here is a type representing either null or a ref.
@ygc369
You can return null as
ref int
by using theUnsafe
class@ygc369
Given that the answer was, “Not possible. Not, unless something is fundamentally broken,” why do you think there would need to be a way to test for
null
? Aref
return can’t benull
, just likeref
parameters can’t benull
, and there’s never been a way to test them for some state that they cannot/shouldn’t be.