ref variable assignment via varname = condition ? ref a : ref b; doesn't work

  • Thread starter Thread starter vpin
  • Start date Start date
V

vpin

Guest
Hello. I was going to report a possible bug in C# VS 2019 with ref variable assignment and was transferred to this site. Please redirect my report to the right place if this is a wrong one. Thanks.

I'm using ref var to work with array1 or array2 depending on some condition.

Here is my test code which works fine:

ValueDataSeries[] arr1 = new ValueDataSeries[10];

ValueDataSeries[] arr2 = new ValueDataSeries[10];
int f=5;
arr1[f] = arr2[f] = null;
ref ValueDataSeries vds = ref arr1[0]; //some mandatory initializer of ref variable vds

if (condition)
vds = ref arr1[f];
else
vds = ref arr2[f];

vds = new ValueDataSeries();


after that I see a reference to a new instance of ValueDataSeries class either in arr1[5] or arr2[5] depending on condition value.

The following modification doesn't work. i.e. there is no error reported and I see var vds is pointed to a new class instance but both arr1[5] and arr2[5] remained equal to null


ValueDataSeries[] arr1 = new ValueDataSeries[10];
ValueDataSeries[] arr2 = new ValueDataSeries[10];
int f=5;
arr1[f] = arr2[f] = null;
ref ValueDataSeries vds = ref arr1[0]; //some mandatory initializer of ref variable vds

vds = condition ? ref arr1[f] : ref arr2[f];

vds = new ValueDataSeries();

Continue reading...
 
Back
Top