Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C# return by reference or value?

Tags:

c#

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

like image 217
Solo116 Avatar asked Dec 08 '22 23:12

Solo116


1 Answers

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.

like image 93
Servy Avatar answered Dec 28 '22 16:12

Servy