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
refparameters, 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
refreturns, if I don’t have any variable to return, the caller probably has to be be told about it somehow (possibly using aboolflag, as you suggested) and I have to somehow allocate storage for the dummy variable on the heap (or it could be astaticfield).So I think it indeed is a bigger issue with
refreturns than withrefparameters.@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 skippingrefand diving straight into pointers.From the blog post above it sounds very much like this request to be able to work with
refas if it’s a “pointer-lite” was never intended. Thatrefas 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 thatrefreturns 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 intby using theUnsafeclass@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? Arefreturn can’t benull, just likerefparameters can’t benull, and there’s never been a way to test them for some state that they cannot/shouldn’t be.