Geeks With Blogs
Abhishek Anand Bits & Bytes about .net technology framework.

As a developer, you have probably run into the situation where you want to return more than 1 value from a method. Even though this can often be a flag for bad function design, there are certain cases where returning 2+ values makes sense. In order to accomplish this functionality in other programming languages like Java, you often would have to create a Data Transfer Object which can become a pain and feel unnecessary. Fortunately C# provides a couple different ways to have “multiple return values”.


1.       Out Arguments - “out” arguments to “return” multiple values from a method, but this makes you rely upon mutation of existing variables rather than returning new values. Also, out arguments rarely play nicely with LINQ Expressions.

 void GetDateValues(DateTime dateTime, out int year, out int month, out int day)
            year = dateTime.Year;
            month = dateTime.Month;
            day = dateTime.DayOfYear;

2.       Tuple<T1, T2…> - .NET provides a data structure called a Tuple, which can be thought of as a row in a database. Tuples can hold 2+ values each corresponding to an item in the “row”.

          var retVal = new Tuple<stringint, DateTime>("Hello", 123, DateTime.Now);
          string item1 = retVal.Item1;
          int item2 = retVal.Item2;


Tuples hold values corresponding to their Generic Type parameters, which in the above example are string and int. The values can then be accessed using the “Item{n}” properties, where {n} corresponds to the index of this item’s type parameter. So in the example above, Item1 is the string value and Item2 is the int value. The downside of using Tuple is that the Item properties do not make for very readable code.


3.       Traditional Data Transfer Objects/Structs – You can still create these Data Transfer Objects as return values where it makes sense to do so. The benefits of using DTOs are that they provide better readability. The downside being that you could end up with a large number of classes in which you only use in one specific situation.

.NET gives you the ability to use any of these methods, but each apply to specific situations so be sure to consider the options before making a decision. Posted on Monday, November 18, 2013 6:54 PM .net , c# | Back to top

Comments on this post: Returning Multiple Values from a Method

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Abhishek Anand | Powered by: