Changing reference values in a List

Viewed 59

I am passing an object of type Entry from a list of Entry into a helper function, which takes in a reference to the Entry object:

for(int i = 0; i < entries.Count; i ++)
{
     Entry singleEntry = entries[i];
     bool success = Helper(ref singleEntry);
}

In the helper function, a new Entry object is created and I want entries[i] to reference the new object instead of the old one, but only singleEntry is actually changed. I tried to do the following:

for(int i = 0; i < entries.Count; i ++)
{     
     bool success = Helper(ref entries[i]);
}

But I got an error: "A property or indexer may not be passed as an out or ref parameter".

I ended up changing entries[i] by adding this line:

for(int i = 0; i < entries.Count; i ++)
{
     Entry singleEntry = entries[i];
     bool success = Helper(ref singleEntry);

     entries[i] = singleEntry;
}

Is there a more elegant solution to changing the references in a List?

1 Answers

Your below portion of code is the best and most commonly accepted way to achieve what you are wanting.

 for(int i = 0; i < entries.Count; i ++)
 {
     Entry singleEntry = entries[i];
     bool success = Helper(ref singleEntry);
     entries[i] = singleEntry;
 }

You also could use the unsafe part of c#(pointers) but that would be very nasty, frowned upon heavily, and might I mention unsafe.

Related