Reputation: 9299
I'm wondering how I should handle return of reference of list from another class? I want to pick the contents of the list from the calling method?
A simplified method that I use to fill a list with numbers and then return the reference of the list
public List<int> Shuffle()
{
code....
return nameOfList;
}
Upvotes: 0
Views: 106
Reputation: 37566
You will have to create the List, fill it and return it, or you can pass it as a parameter, and fill it.
OPTION A
public List<int> Shuffle()
{
nameOfList = new List<int>();
code....
return nameOfList;
}
OPTION B
Call:
Shuffle(ref myList);
Implementation:
public List<int> Shuffle(ref List<int> myList)
{
// work on myList
}
Upvotes: 1
Reputation: 14672
List is a reference type, so a reference will always be returned, even if you instantiate the list in your called method.
Upvotes: 0
Reputation: 137138
This is fine.
The list will be disposed of correctly once the reference in the calling code falls out of scope.
To use the list all you need to do is:
List<int> myList = otherObject.Shuffle();
You need to create the list in your method:
public List<int> Shuffle()
{
List<int> nameOfList = new List<int>();
code....
return nameOfList;
}
Upvotes: 2