Home > OS >  Is it possible to only call a method if a condition is met inside an extension?
Is it possible to only call a method if a condition is met inside an extension?

Time:08-04

I have the following working code:

var cached = Cache.Get(object);
var load = (cached.HasValue)
   ? cached.Value()
   : await GetLoad(object);

Is it possible to make that into an extension? I've tried the following:

public async static Task<T> Else<T>(this Result<T> result, Task<T> fn)
{
    if (result.HasValue)
    {
        return result.Value;
    }
    return await fn;
}
// Called like this:
var cached = Cache.Get(object).Else(GetLoad(object));

But the problem is it ALWAYS calls the GetLoad(object) regardless of the condition being met or not.

What I need is for the GetLoad(object) to ONLY be called if result.HasValue is false.

Thanks in advance!

CodePudding user response:

Instead of taking Task<T> as an argument, you need to take a Func<Task<T>>.

i.e.


public async static Task<T> Else<T>(this Result<T> result, Func<Task<T>> fn)
{
    if (result.HasValue)
    {
        return result.Value;
    }
    return await fn();
}
// Called like this:
var cached = Cache.Get(object).Else(() => GetLoad(object));

With your existing code, GetLoad(object) is resolved so that its result can be passed to Else as a parameter. By passing a func instead you delay execution until the result is needed.

  • Related