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!”

    • 4
  • 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.

    • 2
  • Rajeev Kumar
    Jun, 2023 29

    This program will not return any result because of async method call without using of await.

    • 0
  • Tuhin Paul
    Apr, 2023 15

    In the Main() method, PrintAsync() is called, but since it is an asynchronous method, it returns immediately before its task is complete. The Console.WriteLine(result) statement executes and prints the current value of result, which is still null because the task returned by PrintAsync() hasn’t finished yet.

    When the task finally completes after the 5 millisecond delay, it sets the value of result to “Hello world!”, but this happens after the Console.WriteLine(result) statement has already executed. Therefore, the output of the program is null.

    • 0
  • Tuhin Paul
    Apr, 2023 15

    The output of this program will be null

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS