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.
4 Answers
Needs a return :
return Task.Factory.StartNew(() => { Console.WriteLine("Hello Task library!"); });
Or better:
return Task.Run(() => { Console.WriteLine("Hello Task library!"); });
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