0

I'm trying to store all fields in an array and then multiply each field by * 3

public class Person
{
    public int Field;
    public int Field2;
}

var p = new Person {Field = 8};
int[] items = { ref p.Field, ref p.Field2 }; //this is not allowed

for (int i = 0; i < items.Length; i++)
{
    ref int ret = ref items[i];
    ret *= 3;
}

Expected p.Field is 24. Is it possible to do so? If not, is it possible to do it with properties instead of fields?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
MistyK
  • 6,055
  • 2
  • 42
  • 76
  • Is `ref int ret = ref items[i];` valid C# syntax? – Uwe Keim Jul 11 '19 at 12:59
  • 1
    @UweKeim Yes it is. – Lasse V. Karlsen Jul 11 '19 at 13:00
  • 4
    You can not store references to variables other than up/down the call stack. They're not meant as a way to *store* data, they're meant as a way to optimize calls to methods. I don't see how properties will make this remotely useful either. Can you tell us **why** you want to do this? – Lasse V. Karlsen Jul 11 '19 at 13:01
  • 1
    @LasseVågsætherKarlsen [OMFG ](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ref#reference-return-values) I didn't have a clue about all those `ref` possibilities. – Uwe Keim Jul 11 '19 at 13:06
  • Possible duplicate of [How do I assign by "reference" to a class field in c#?](https://stackoverflow.com/questions/2980463/how-do-i-assign-by-reference-to-a-class-field-in-c) – Kacper Turowski Jul 11 '19 at 13:17
  • @LasseVågsætherKarlsen I'm trying to batch update some fields in a loop. For example I want to list fields and then for each field check condition and then update it, e.g if(field > 3) fields* 3 and it will update it. I can do it with reflection, I can do it with expression trees but I thought ref will make it easier. – MistyK Jul 11 '19 at 13:20
  • @KacperTurowski I found Eric's solution and it's fine. However I expected that new feature with ref will give me a way to make it easier. – MistyK Jul 11 '19 at 13:23

0 Answers0