Wanting to return more than one thing from a method is a pretty common scenario. For example, a response and how long it took to retrieve it.
Like anything, there’s more than one way to go about this. You could use an out (or ref) parameter:
public void DoIt() { TimeSpan duration; var response = GetResponse(out duration); // do something with response & duration } private string GetResponse(out TimeSpan duration) { var stopwatch = Stopwatch.StartNew(); var response = ...; stopwatch.Stop(); duration = stopwatch.Elapsed; return response; }
Or return a (private nested) class, or struct:
public void DoIt() { var result = GetResponse(); // do something with result.Response & result.Duration } private Result GetResponse() { var stopwatch = Stopwatch.StartNew(); var response = ...; stopwatch.Stop(); return new Result { Response = response, Duration = stopwatch.Elapsed }; } private class Result { public string Response { get; set; } public TimeSpan Duration { get; set; } }
But .NET 4.0 gives us one more option, an anonymous type:
public void DoIt() { var result = GetResponse(); // do something with result.Response & result.Duration } private dynamic GetResponse() { var stopwatch = Stopwatch.StartNew(); var response = ...; stopwatch.Stop(); return new { Response = response, Duration = stopwatch.Elapsed }; }
Same effect, less code!