What should be the execution result of the following code?

using System;
using System.Threading.Tasks;

using static System.Console;
using static System.IO.File;

class Program
{
    static void Main(string[] args)
    {
        Run();
        ReadLine();
    }
    static void Run()
    {
        var task = ComputeFileLengthAsync(null);
        WriteLine("Computing file length");
        WriteLine(task.Result);
        WriteLine("done!");
    }

    static async Task<int> ComputeFileLengthAsync(string fileName)
    {
        WriteLine("Before If");
        if (fileName == null)
        {
            WriteLine("Inside");
            throw new ArgumentNullException(nameof(fileName));
        }
        WriteLine("After");

        using (var fileStream = OpenText(fileName))
        {
            var content = await fileStream.ReadToEndAsync();
            return content.Length;
        }
    }
}

Hint: it will print “Computing file length” on the output.

Now, can you figure out why? What implementation strategy could I follow to get the exception when calling the function?

This Post Has One Comment

Leave a Reply