Naimish Makwana
What is the output of the program below? Give an explanation.
  1. public class TestAsync
  2. {
  3. private static string result;
  4. static void Main()
  5. {
  6. PrintAsync();
  7. Console.WriteLine(result);
  8. }
  9. static async Task<string> PrintAsync()
  10. {
  11. await Task.Delay(5);
  12. result = "Hello world!";
  13. return "This is example";
  14. }
  15. }
By Naimish Makwana in C# on Jan 17 2023
  • Jignesh Kumar
    Jan, 2023 25

    Above code snippet will not return any result because of async method call without await.

    if you are expeting to execute then you can call in two ways,

    1. var r = PrintAsync().Result;

    Another way you have to call with await keyword then will return result as “Hello world!”

    • 3
  • Jin Vincent Necesario
    Feb, 2023 4

    This will not show any result on the screen.
    I agree with Jignesh

    Just to add we can also add the async and Task keyword into the Main method so we can add the asyncbefore the PrintAsync method. Although this is supported starting at C# 7.1.

    1. static async Task Main(string[] args)
    2. {
    3. var r = await PrintAsync();
    4. Console.WriteLine(r); //This is example
    5. Console.WriteLine(result); //Hello World
    6. Console.ReadLine();
    7. }

    Hope this helps. Thanks.

    • 1


Most Popular Job Functions


MOST LIKED QUESTIONS