简体   繁体   中英

Can I declare named async tuple functions in C#?

C# 7 allows us to declare functions that return named tuples, so a declaration like the one illustrated below is now ok.

(int quotient, int remainder) = GetDivisionResults(17, 5);

I have need to process the response from an HTTP Client request and extract two values from it, and I want to do so asynchronously. The following is allowed

public static async Task<<Tuple<string,string>> GetRequiredReturnValuesFromResponse(string response)

My simple question is, is it possible to name the output strings in the same way that I could were the function to operate synchronously along the lines as illustrated below?

public static async Task<Tuple< string OrderNumber,string OriginalId>> GetRequiredReturnValuesFromResponse(string response)

You can't name Tuple elements - only ValueTuple elements. C# 7 tuple support is based on the ValueTuple type. But even then, the names aren't part of ValueTuple itself... they're stored in attributes alongside the return type (or parameter type).

So you can definitely declare this:

public static async Task<(string OrderNumber, string OriginalId)>
    GetRequiredReturnValuesFromResponse(string response)

You can then use:

var tuple = await GetRequiredReturnValuesFromResponse(response);
Console.WriteLine(tuple.OrderNumber);
Console.WriteLine(tuple.OriginalId);

Or even:

var (number, id) = await GetRequiredReturnValuesFromResponse(response);

But you can't name the elements when explicitly using ValueTuple (unless you specify the naming attributes explicitly, which I believe the compiler warns you against anyway) or using Tuple at all.

Personally I'd recommend against putting ValueTuple types in public APIs; I typically regard them as a stop-gap measure for an internal implementation which I might decide to migrate to a more fully-encapsulated type later on. But that's just a personal opinion, and doesn't represent what you can do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM