One way to avoid the async part of the wait is to make the extension method work with the type returned inside the Task
public static T ThrowIfNull<T>(this T obj, string message) where T : class { if (obj == null) throw new HttpException(404, string.Format(Resources.GenericNotFound, message)); return obj; }
I made a general extension method since I donβt know what type of model . Then you can just use it like that.
var model = (await this._service.GetAsync(id)).ThrowIfNull("List item");
By placing await in brackets, you make sure that it will wait for the task and expand it before passing the result to the extension method.
Another option is to make the extension method work on Task<T>
public static async Task<T> ThrowIfNullAsync<T>(this Task<T> task, string message) where T : class { var obj = await task; if (obj == null) throw new HttpException(404, string.Format(Resources.GenericNotFound, message)); return obj; }
And you do not need a bracket.
var model = await this._service.GetAsync(id).ThrowIfNullAsync("List item");
But this means that the exception is now wrapped up in a task, which may or may not be desirable depending on how you use this method.
source share