Having a C # method return more than one value for different data types?
7 replies
Create an object with properties for the values โโyou want to return:
public class MyReturnType
{
public string[] MyStringArray { get; set; }
public double[] MyDoubleArray { get; set; }
}
Then your method will return this new type:
public MyReturnType Foo()
{
...
return new MyReturnType { MyStringArray = strings; MyDoubleArray = doubles; };
}
+10
a source to share
-
Using a Tuple struct (new in .NET 4.0, but you can just create it in your own dll based on it - it's a simple container for a few generic types).
-
Use a specialized carrier structure like Michael Shimmins answer, but make it a structure rather than a class if it's not big.
-
Use dicitonary or object array if it's purely internal function (case problems).
-
Use parameters.
+7
a source to share
You can return Hashtable
objects. Or a List
... or whatever kind of collection of objects you want.
LE:
Hashtable process(string[] x, double[] y)
{
Hashtable output = new Hashtable();
// do whatever you want with x and y
output["stringArray"] = x;
output["doubleArray"] = y;
return output;
}
// ...
string[] stringArray = new string[] {};
double[] doubleArray = new double[] {};
// ...
Hashtable outcome = process(stringArray, doubleArray);
string[] data1 = (string[])outcome["stringArray"];
double[] data2 = (double[])outcome["doubleArray"];
// ...
-3
a source to share