*** #3.1 How to return multiple values from method***
Quick one today – how to write a method that returns more than one value. There are two ways: i) use out keyword, ii) use generic class Tuple. In the first approach we return first value as we usually do, the second value will be passed as parameter with out keyword. Take a look at example method:
1 2 3 4 5 |
public string OutMethod(int param, out string returned) { returned = String.Format("This is set by method: {0}", param); return String.Format("This is returned value: {0}", param); } |
Now if we want to make use of this method we either need to have a variable pre-declared and pass it into the method or declare it inline in the place of invocation:
1 2 3 4 5 6 7 8 9 10 |
//out method - pre-declared string value2P; string value1P = OutMethod(9, out value2P); Console.WriteLine(value1P); Console.WriteLine(value2P); //out method - inline declaration string value1 = OutMethod(9, out string value2); Console.WriteLine(value1); Console.WriteLine(value2); |
Nice and simple, right? It the second approach we make use of Tuple generic class. It works with up to 8 generic parameters meaning that we can return 8 values (but nobody says that one of the returned values is another tuple, so in practice we can go for how many values as we want). Here’s an example:
1 2 3 4 5 6 |
public Tuple<string, string> TupleMethod(int param) { string value1 = String.Format("This is set by method: {0}", param); string value2 = String.Format("This is returned value: {0}", param); return new Tuple<string, string>(value1, value2); } |
So this method in fact returns one value of type Tuple. So how to access the values we really want?
1 2 3 4 5 6 |
//tuple method var result = TupleMethod(9); string valueA = result.Item1; string valueB = result.Item2; Console.WriteLine(valueA); Console.WriteLine(valueB); |
Again, nice and simple. Which way is better? I guess the one you prefer 🙂