Friday, September 9, 2011

Returning more than one value from a method.

Reading "More Effective C#" I came across a pretty cool bit (around p.55) about using the tuple type to return more than one value from a method. That's fair enough but the really cool part was the way the author used the using keyword...

For example, in returning a latitude, longitude from a method (you could be returning five or six values etc. with a tuple but lets use two for simplicity) Tuple<int, int> doesn't really tell us too much.
public static Tuple<string, decimal> GetLocation(string address)
{
   int longitude = // get longitude algorithm
   int latitude = // get latitude algorithm
   return new Tuple<int, int>(longitude, latitude);
}

//usage
Tuple<int, int> weather = GetLocation("address");

To give a more meaningful return name you can provide an alias for the return value. 
using GeoLocation = Tuple<int, int>;
public static GeoLocation GetLocation(string address)
{
   int longitude = // get longitude algorithm
   int latitude = // get latitude algorithm
   return new GeoLocation(longitude, latitude);
}

// usage
GeoLocation location = GetLocation("address");

The using keyword continues to surprise me (e.g. as a tidy way of attempting to dispose of something without knowing whether or not it implements IDisposable). Of course if this method was simply better named "GeoLocation" there's be no problem! But it's the concept that's useful to know.

No comments:

Post a Comment