Out parameters in Async methods.

A little while ago, I wanted to have an asynchronous method that returned a string but also populated an integer “out” parameter. So I started writing the method as below

// Note: This will give compiler error.
private async Task<string> GetUserDetails(out int userRegionCode)
    return "samplestring";

However, the compiler showed an error stating that out parameters were not allowed for an asynchronous method. After searching for it online and reading through this thread (gives a detailed explanation), I found that it’s a limitation of the CLR.

So instead I used a Tuple to return both the values that I wanted to use. You can read more about Tuple and its usages here.

Sample code below.

// calling code. 
var userDetails = await GetUserDetails(userId); 
Console.WriteLine("Username : {0}", userDetails.Item1); 
Console.WriteLine("User Region Id : {0}", userDetails.Item2); 

private async Tuple<string,int> GetUserDetails(int userId) 
    return new Tuple<string,int>("Amogh",105); 
    // Note that I can also use the existing helper method (Tuple.Create) here. Read more about it here. 

Hope this helps!

This entry was posted in .NET and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *