Alex Rivera | Logout

What is the best way to return two lists in C#?

Asked 2009-07-08T16:25:28.190
15

I am almost embarrassed to ask this question, but as a long time C programmer I feel that perhaps I am not aware of the best way to do this in C#.

I have a member function that I need to return two lists of a custom type (List<MyType>) and I know beforehand that I will always have a return value of only two of these lists.

The obvious options are :

public List<List<MyType>> ReturnTwoLists();

or

public void ReturnTwoLists(ref List<MyType> listOne, ref List<myType> listTwo);

Both seem to be non-optimal.

Any suggestions on how to improve this?

The first way doesn't make it clear in the syntax that only 2 lists are being returned, and the second uses references rather then a return value, which seem so non-c#.

Edit
Report

1 Answer

4

Your first suggestion isn't two lists. It's a list of lists.

The second option would do what you intend, but you might want to change it to use the out keyword instead of ref so the callers of your method will know the intention of what you're doing.

public void ReturnTwoLists(out List<MyType> listOne, out List<myType> listTwo);
answered 2009-07-08T16:29:27.793

Your Answer