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!
Or you could use a Tuple, less exciting – but the same effect.
I often wish C# could return multiple values Python style. Perhaps I should use a dynamic language instead, and shut up.
Yep, forgot that one! They are pretty fugly in C# though, and I’m not that keen on result.Item1 :(
Great tip, thanks Graeme.
You’re welcome, Bin.