Returning more than one thing from a method in C#

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!

Advertisements

4 thoughts on “Returning more than one thing from a method in C#

  1. Richard November 7, 2011 / 10:05 am

    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.

  2. grahamrhay November 8, 2011 / 7:47 pm

    Yep, forgot that one! They are pretty fugly in C# though, and I’m not that keen on result.Item1 :(

  3. benbiddington November 14, 2011 / 8:37 am

    Great tip, thanks Graeme.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s