I need to return multiple items from a function. How can I do that?
public List<string> GetInfo()
{
var result = new List<string>();
return result;
}
How can I return something like this? Basically List of string and maybe also a list of generic type.
public List<string> GetInfo()
{
var result = new List<string>();
return result and someType;
}
public class someType
{
public List<SomeOthertype> someOthertype { get; set; }
}
CodePudding user response:
If I understand you right, you can try using named tuples:
public (List<string> result, List<SomeOthertype> other) GetInfo()
{
var result = new List<string>();
someType instance = new someType();
//TODO: put relevant code here
// we return both result and someOthertype in one tuple
return (result, instance.someOthertype);
}
Usage:
var info = GetInfo();
var result = info.result;
var other = info.other;
CodePudding user response:
I would propose to use a generic method to be possible use different types:
public static (List<string>, List<U>) GetInfo<U>()
{
var list = new List<string>();
var another = new List<U>();
//...
return (list, another);
}
CodePudding user response:
From c# 7 onward there are tuple value types that are the cleanest way to return multiple values from the function.
Pre c# 7 you can use out parameters