Is it better to return an empty task or null? c#

Viewed 34744

I have an asynchronous method which will look for a jobId for a job scheduling service through an Api.

if it finds no results is it better to return an empty task or null?

As i understand when returning a collection it is better to return an empty collection rather than null and using objects its better to return null than an empty object; but with tasks i am unsure which is best. See attached method.

Thank you

   public virtual Task<int> GetJobRunIdAsync(int jobId)
        {
            var jobMonRequest = new jobmonRequest(true, true, true, true, true, 
            true, true, true, true, true, true, true,
            true,
            true, true, true, DateTime.Today, jobId, null, 0, null, null,
            null, null, 0, 0);

        var jobMonResponseTask = Client.jobmonAsync(jobMonRequest);

        var jobTask = jobMonResponseTask.ContinueWith(task =>
        {
            if (jobMonResponseTask.Result == null )
            {
                var empty = new Task<int>(() => 0); // as i understand creating a task with a predefined result will reduce overhead.

                return empty.Result;   // || is it better to just return null?
            }
            if (jobMonResponseTask.Result.jobrun.Length > 1)
            {
                throw  new Exception("More than one job found, Wizards are abound.");
            }
              return jobMonResponseTask.Result.jobrun.Single().id;
        });

        return jobTask;
    }
6 Answers

The answer from Stephen Cleary explains it perfectly: do never return null, or you'll provoke null reference exceptions but I want to add something:

If you return null instead of a completed task, this code will throw a null reference exception:

await FunctionThatShouldRetunrTaskButReturnsNull();

and it's a bit difficult to understand what's going on even when you see it in the debugger.

So, never, never, return a null from a non-async function that returns a Task.

Explanation:

  • in a non-async function, that returns a Task or Task<T>, you need to create the task explicitly, and there is the danger of returning null instead of a task.
  • in an async function that returns a Task or Task<T>, you simply return or return a value, and the result of the function is implicitly converted to a task, so there is no danger of returning null.

If you really want to return null from async method, you can use Task.FromResult(null)

For example:

public async Task<FileInfo> GetInfo()
{
    return await Task.FromResult<FileInfo>(null);
}
Related