1

I've a method like this:

public async Task<Response> HandleRequest(string connectionId, Request request)
{
  if (request is AuthorizeRequest)
  {
    return await _handler.HandleRequest(connectionId, request as AuthorizeRequest);
  }

  if (request is ChangeConfigurationRequest)
  {
    return await _handler.HandleRequest(connectionId, request as ChangeConfigurationRequest);
  }

  return await Task.FromResult<Response>(null);  //My question is here
}

My question is: Should I return return await Task.FromResult(null); or retun null; Because if request is not 'AuthorizeRequest' and 'ChangeConfigurationRequest'

Tks all for helps

2 Answers 2

2

Since your method is marked as async, you should return null.

Sign up to request clarification or add additional context in comments.

3 Comments

Tks Peres, I search from many resources and it said that we should not return null in Task. Is it right?
And how about my method like this: ``` public Task<Response> HandleRequest(string connectionId, Request request) { return Task.FromResult<Response>(null); }```
Yes, that would be correct, IMO, without the async modifier.
2

I search from many resources and it said that we should not return null in Task. Is it right?

Methods that return a task should never return a null task. However, what you want to do is return a (non-null) task that contains a result value of null. That's fine; it's completely different than returning a null task.

For your original code, use return null;. Do not ever use await Task.FromResult(...).

2 Comments

I know this is an old post, but when would one ever need to use Task.FromResult()? Is it only when we are dealing with a method that is not async returns a Task? Is there ever a reason in modern C# to have a method that returns a Task without also being async anyway?
It's rare. Most of my use cases are test stubs implementing async interfaces.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.