I am creating a method with this signature
public Task RunThisFunction(Func<Task> func)
now the user of this method can use it with a function like this as the parameter
public Task GetThingsDone(){await DoSomething();}
No surprises there, but it also seems that you can send in functions like this
public Task<string> GetString(){await return GetSomething();}
Why is that and how would I write a signature to prevent the latter to be sent in to RunThisFunction?
CodePudding user response:
The Task<T>
class inherits the Task
class, so a method that returns a Task<string>
IS returning a Task
. You generally can't provide a less specific type where a more specific type is expected, because it won't have the additional members that the more specific type does. You generally can provide a more specific type where a less specific type is expected because it will have all the members that the less specific type does. If you have code that accesses the members of the Task
class and you pass in a Task<string>
then the code will work because the Task<string>
object has all those members.
CodePudding user response:
if I understand correctly, you can try to use the overload method passing Func<Task<string>>
for RunThisFunction
method
public async Task<string> RunThisFunction(Func<Task<string>> func){
return await func();
}