Monday, January 23, 2012

C# out Parameter–Tuples (Multiple return values)

There will be times when you want to get multiple return values from methods and are to lazy to create a new object for it. Well recently the .NET framework now supports a couple of ways to return multiple values with more ease.
First of all we have the “Tuple” being now available and coming from the F# side of the .NET framework. A tuple is no more then a typesafe way to return a collection of different objects. As an example:

   1: public Tuple<string,int,double> TupleReturn()
   2: {
   3:     //... some DB action
   4:     return Tuple.Create("FirstItem", 1, 500.00);
   5: }

This method return as tuple with the first item being a string, the second an integer and the third a double. To work with this return value we can do the following:


   1: var x = TupleReturn();
   2: var i1 = x.Item1;
   3: var i2 = x.Item2;
   4: var i3 = x.Item3;
   5:  
   6: Console.WriteLine(String.Format("The type of i1 is {0}",i1.GetType()));
   7: Console.WriteLine(String.Format("The type of i2 is {0}",i2.GetType()));
   8: Console.WriteLine(String.Format("The type of i3 is {0}",i3.GetType()));
   9: Console.ReadLine();

The result will be:


  • The type of i1 is System.String
  • The type of i2 is System.Int32
  • The type of i3 is System.Double

To read more about tuples go to: MSDN (1) or Extended Tuples


The next solution to return multiple is to work with the “out” parameter. This type of method parameter allows for the method to use the same variable as it was passed to it. So in short, any change to the parameter will be reflected to the variable passed to it. Next to this, the method itself can off course still return a normal value.



   1: public string OutReturn(out string name, out string surName)
   2: {
   3:     //... some DB action
   4:     name = "Ferrari";
   5:     surName = "Bently";
   6:     return "are awesome!";
   7: }

The one thing to not about this type of parameter is that is has to be initialized before you pass it to the method! If you do so, you can use it as follows:


   1: string name;
   2: string surName;
   3: var r = OutReturn(out name,out surName);
   4: Console.WriteLine(String.Format("{0} and {1} {2}",name,surName,r));
   5: Console.ReadLine();


Which results into:
Ferrari and Bently are awsome!


Enjoy!

No comments:

Post a Comment