-4

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.

steve
  • 21
  • 1
  • 3

1 Answers1

2

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.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • @AlexeiLevenkov True, but the error in that case is relatively clear: "A property, indexer or dynamic member access may not be passed as an out or ref parameter" I wouldn't call it "one of the most puzzling warning/behaviors in C#" ;) – Reed Copsey Jun 12 '13 at 23:30
  • +1: (updated comment) Side note that it works only with arrays - see Reed's comment on what will happen if you use other collection. (On the puzzling warning - I confused it with different scenario - calling mutating method on value type stored in a collection - works fine with arrays, but nothing else) – Alexei Levenkov Jun 12 '13 at 23:41
  • Thanks for the help guys. On a side note, if an array contains reference types, can you modify the reference itself in a similar way? If so, does this too only work with arrays as you described? P.S. I'd upvote your answer if my rep was high enough. :) – steve Jun 13 '13 at 20:55
  • @steve Yes, it works on reference types in arrays. And yes, the issue with only working with array is the same. – Reed Copsey Jun 13 '13 at 21:36