Task Return Type Gives Not All Code Paths Return a Value

Task Return Type Gives Not All Code Paths Return a Value

I have a method implemented from an interface which looks as follows..

public Task CreateAsync(ApplicationUser user)
{
     if (user == null)
     {
         throw new ArgumentNullException("user");
     }
     Task.Factory.StartNew(() => { Console.WriteLine("Hello Task library!"); }); 
     //I even tried
     //Task.Run(() => { Console.WriteLine("Hello Task library!"); });

}

The above code gives me an error not all code paths return a value.

2

4 Answers

Needs a return :

 return Task.Factory.StartNew(() => { Console.WriteLine("Hello Task library!"); });

Or better:

return Task.Run(() => { Console.WriteLine("Hello Task library!"); });
1

returning Task.CompletedTask is cleaner.

public Task CreateAsync(ApplicationUser user)
{
  if (user == null)
  {
     throw new ArgumentNullException("user");
  }

   Task.Factory.StartNew(() => { Console.WriteLine("Hello Task library!"); }); 
   // other operations

   return Task.CompletedTask;
 }

The parameter Task in the name of your method denotes the return value of this method.

Therefore the compiler expects at a certain point your method a return statement where you return an object of that type that you denoted in the name.

public Task CreateAsync(ApplicationUser user)
{

     if (user == null)
     {
         // this part of code will return from the method with an exception
         throw new ArgumentNullException("user");
     }

     // but this part of code is also expected to return something
     return Task.Run(() => { Console.WriteLine("Hello Task library!"); });

}

Needs a return ..if possible one inside the if condition also and one outside

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.