EDIT
Here is a better explaination to my problem. Especially to answer to question "Why I want to use references, and why not just use double?
".
So I actually have the following variables:
double? Left_A, Left_B;
double? Right_A, Right_B;
double? Result_Left, Result_Right;
The user either sets value of the left variables, or the right ones. It is handled in my ViewModel. I am calculating the values of results, based on
some formulas like result = a * b
etc.
The formulas are the same for left or right variables.
So I just wanted to create a "pointer" like reference variables, 'a' and 'b', whose value would be the value of Left_A
or Left_B
so that I don't have to do the following:
if(Left_A != null) {
Result_Left = Left_A * Left_B;
} else {
Result_Right = Right_A * Right_B;
}
//There are more such formulas for many use-cases..
I wanted something like this..
ref double? result, a, b;
a = ref Left_A ?? ref Right_A; //This gives error.
b = ref (Left_B ?? Right_B); //This gives error.
result = Result_Left ?? Result_Right;
result = a * b;
I hope I am not doing something wrong in this..
I am trying to use the Null-coalescing operator with the ref
keyword
My assignment statement is as follows:
Note: According to my business logic which is omitted here, it is guaranteed that both a & b won't be null. Either of them will have a value.
double? x = a ?? b; // a and b are also of type "double?".
However I want x
to be a reference type variable. Is this possible?
I tried the following, but all of them give compilation errors. Especially the last one:
ref double? x = ref (a ?? b);
ref double? x = ref a ?? ref b;
ref double? x = (ref a) ?? (ref b);
ref double? param1 = ref ( please work!!! -.-' );
Any ideas?
It can be done with a method:
ref double? GetValue(ref double? a, ref double? b) {
if (a == null) return ref b; else return ref a;
}
then,
ref double? x = ref GetValue(ref a, ref b);
I don't think it can be done using the null-coalescing operator.