Pregunta

It is safe to modify value types in an array through a method which uses a ref to the element in the array, as shown below? If so, what kinds of value types can be modified this way? Is it limited to simple value types or will struct also work?

// Method that sets an integer to x.
void SetToX(ref int element, int x) {
    element = x;
}

// Int array with one element set to 0.
int[] myIntArray = new int[1] {0};

// (Try to) set element 0 of the int array to 1.
SetToX(ref myIntArray[0], 1);

// Will this log "0" or "1"?
Log(myIntArray[0].ToString()); 

Answer courtesy of Reed Copsey and Alexei Levenkov

This works fine - the sample code will print "1". This also works with any value type including struct.

However, this is ONLY the case with arrays. If you attempt to modify another kind of collection this way, you will be prompted with:

A property, indexer or dynamic member access may not be passed as an out or ref parameter

This is because only arrays actually return a reference to the value type in the element. All other collections will return a copy of the element, and using ref will modify the copy, leaving the original untouched.

¿Fue útil?

Solución

Yes, this works fine.

Your sample code will print:

1

If so, what kinds of value types can be modified this way? Is it limited to simple value types or will structs also work?

Any value types. A custom struct will have the same behavior.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top