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)
{
    userRegionCode=105;
    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!

Advertisements

About Amogh Natu

Technology enthusiast, Associate Consultant @ Microsoft, music lover, love my guitar, Microsoft.NET, ASP.NET, C#.NET Professional.
This entry was posted in .NET and tagged , , , . Bookmark the permalink.

Your comments or opinions.....

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