Returning 2 values from a method
This is for a mathematical method that takes in 3 doubles as input (a, b,c ).
Next those 3 values get calc开发者_StackOverflow中文版ulated in a formula (abc formula for square roots).
The formula has 2 values that have to be returned but how exactly do i do this?
I was thinking of a array / objects, but not sure how to initialise them for this purpose. Out parameters are not really of any use in this situation are they?
Regards.
In C# 4 (available in Visual Studio 2010):
Tuple<double, double> Foo(double a, double b, double c)
{
...
return Tuple.Create(firstReturnValue, secondReturnValue);
}
If you're working with an earlier language version of C#, you can define your own implementation of a two-tuple (pair) as follows:
public struct Tuple<A, B>
{
public readonly A Item1;
public readonly B Item2;
public Tuple(A a, B b) { Item1 = a; Item2 = b; }
}
public static class Tuple
{
public static Tuple<A,B> Create<A,B>(A a, B b) { return new Tuple<A,B>(a,b); }
}
Of course, Tuple
is a very general and unspecific data type. You could just as well implement a composite return type (similar to what I just showed, but simpler) that is more specific to your situation.
Use out:
double t;
int y = Foo(5,3,out t);
def:
public int Foo(int one,int two,out double three) {
three = one / two;
return one + two;
}
http://msdn.microsoft.com/en-us/library/ee332485.aspx
In C# 4 , you can do same as Tuple as described by staks above
but below c#4 , you can return a list which contains as many as values you want to return.
I'd create a class for the purpose, of even a simple struct, but a Tuple (like stakx suggested) is just as good, and even a list or a collection can do the trick.
An array is not very favorable, since you just have a bunch of items, without any further information about them, really. The caller has to somehow "know" what element no. 0, element no. 1 is.
In such a case, I would always vote for using a class - define a return type as a class, give the individual fields meaningful names. A class gives you discoverability (through field names), the ability to mix the return types (return an INT, two DECIMAL, a STRING), and it nicely encapsulates your results:
public class ResultType
{
decimal Value { get; set; }
decimal AnotherValue { get; set; }
int StatusCode { get; set; }
string Message { get; set; }
}
and then define your method as:
ResultType YourMethodName(double a, double b, double c)
{
ResultType result = new ResultType();
// do your calculations here......
result.Value = .........
result.AnotherValue = ............
result.StatusCode = 0;
result.Message = "everything OK";
return result;
}
精彩评论