r3plica r3plica - 3 months ago 19
C# Question

Static Method for handling null returns

So I have created a provider (a few of them actually) and I am realising there is a bit of a pattern in some of my logic. It is being repeated and I reckon I can remove lots of lines of code if I can just create this extension method :D

So, basically what is happening is something like this:

// Get our item to be deleted
var model = await this._service.GetAsync(id);

// If we have nothing, throw an error
if (model == null)
throw new HttpException(404, string.Format(Resources.GenericNotFound, "List item"));


Now, I do this in a lot of places, not just for deleting, but for updating.
I would like to create an extension method that allows me to do something like this:

// Get our item to be deleted
var model = await this._service.GetAsync(id).ThowIfNull("List item");


I also need this to work with any return type. So in this case it might be an Account, but there will be a provider that also has this code returning an Order but I need the extension method to work for both.

I think the challenge here is the async bit, but I might be wrong!

Anyone know if it is possible?

Answer

One possibility to avoid the async-await part is to make the extension method work on the type returned inside of 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 the extension method generic as I don't know what type model is. Then you can just use it like this.

var model = (await this._service.GetAsync(id)).ThrowIfNull("List item");

By putting the await in parenthesis you make sure it will wait on the task and unwrap it before passing the result to the extension method.

Comments