Having a C # method return more than one value for different data types?

I have a function that takes two parameters:

 string[], double[]

      

How do I return both of these values? How do I call this function?

+2


a source to share


7 replies


Hey, you can use the "out" keyword:



column s1;
column s2;

public void method1(out value1, out value2)
{
select col1, col2, from tb1
value1 = col1;
value2 = col2;
}

      

+11


a source


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


  • 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


You can use out or ref parameter.

See here and here

+2


a source


you cannot return this directly, but you can return this with strct. you can create a structure for string and double and store the value in it, after which you can return it.

0


a source


you can also use ref operator

0


a source


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







All Articles