Task.FromResult(obj) doesnt return null value

Question

Monday, March 26, 2018 12:09 PM

in my scenario i want to return null value on some condition and sometime want to return object

but it always returning obj not null value.

can anyone give me the appraoch for this

Vinod

All replies (2)

Wednesday, March 28, 2018 6:30 AM

Hello Vinod,

The MSDN has detailed description with Task.FromResult method.

This method creates a Task<TResult> object whose Task<TResult>.Result property is result and whose Status property is TaskStatus.RanToCompletion. The method is commonly used when the return value of a task is immediately known without executing a longer code path. The example provides an illustration.

So the return stuff must be task<TResult> object and if you want to generate a task whose result is null, the code like below.

          var ta=  Task.FromResult<object>(null);
          var result = ta.Result;

If you have any issues, please feel free to contact me.

Best Regards,

Neil Hu

MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


Wednesday, March 28, 2018 2:45 PM

You can certainly pass back null from a task. Please post the code you are having an issue with.

Michael Taylor http://www.michaeltaylorp3.net