In the following scenario, would "Pool" be returned by value or by reference?
private static List<Item> Pool;
public static List<Item> GetPool()
{
return Pool;
}
I want to achieve the ability to loop through the list at the time it was requested (so that another thread could add/remove items from the list but the calling thread's list stays the same so that the foreach loop does not cause an exception). If it was returned by value then it would be its own list whereas if it was a reference, I'd still be in danger of the list being modified. Please correct me if anything is wrong, this is just my understanding
All methods always return a value. They can never return a reference.
If it was returned by value then it would be its own list whereas if it was a reference, I'd still be in danger of the list being modified.
That is false. The value being returned is not the list, but a reference to the list object, because List
is a reference type, so any code using the value returned from this method and any code accessing that field directly are using different copies of references to the same list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With