No, you canβt.
You can still edit items in place, but only by assigning them directly:
vars[2] += 42;
But I just tested this:
using System; public class Test { private static void assign(ref int i) { i = 42; } public static void Main() { var vars = new [] { 1,2,3,4 }; Console.WriteLine(vars[2]); assign(ref vars[2]); Console.WriteLine(vars[2]); } }
See LIVE http://ideone.com/fz36y
Exit
3 42
Update: Wrapper
As a mental exercise, I came up with this sick and twisted mechanism to still get what you want (but at an even higher price than just boxing all the ints):
private class Wrap<T> where T : struct { public T Value; public static implicit operator Wrap<T>(T v) { return new Wrap<T> { Value = v }; } public static implicit operator T(Wrap<T> w) { return w.Value; } public override string ToString() { return Value.ToString(); } public override int GetHashCode() { return Value.GetHashCode(); }
Now Wrap<int>
will behave roughly like a regular int (more work is needed in the areas of comparison, equality, and operators). You can use it to write this, and work the way you wanted:
private static void assign(ref int i) { i = 42; } public static void Main() { Wrap<int> element = 7; var vars = new Wrap<int>[] {1, 2, element, 3, 4}; Console.WriteLine(vars[2]); assign(ref vars[2].Value); Console.WriteLine(element); Console.ReadKey(); }
Conclusion:
7 42
Check out live: http://ideone.com/b0m7T
source share