Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the replacement of Out keyword for Async methods in .Net 4.5 and 4.0?

All i want to use Out keyword with my Async function. According to MSDN it is not possible Async modifiers not supports to the out keyword. So is there any alternate in .Net framework 4.5/4.0 ?

like image 929
Ashish-BeJovial Avatar asked Feb 05 '14 07:02

Ashish-BeJovial


People also ask

What is async keyword in C#?

The async keyword turns a method into an async method, which allows you to use the await keyword in its body. When the await keyword is applied, it suspends the calling method and yields control back to its caller until the awaited task is complete. await can only be used inside an async method.

What happens when you call async method without await C#?

The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.

Can we use async without await C#?

The warning is exactly right: if you mark your method async but don't use await anywhere, then your method won't be asynchronous. If you call it, all the code inside the method will execute synchronously.


1 Answers

You can declare the async function to return Tuple instead. With that the function still able to return multiple values without using out parameter.

public async Task<Tuple<string, int, bool>>SomeFunctionAsync()
{
    return new Tuple<string, int, bool>("foo", 0, false);
}

For Reference :

  • Tuple Class
  • Why async methods cannot have ref or out parameters?

UPDATE :

you can use shorter syntax as suggested by @svick in comment. Following function return the same value, but using Tuple.Create :

public async Task<Tuple<string, int, bool>>SomeFunctionAsync()
{
    return Tuple.Create("foo", 0, false);
}
like image 195
har07 Avatar answered Oct 23 '22 14:10

har07