Search code examples
c#extension-methodsfunc

ExtensionMethod ThrowIf Invert Func<T,bool>


I have written an extension method which throws an Exception if a boolean function evaluates to true/false for a given type T.

    public static void ThrowIf<T>(this T source, Func<T,bool> func, string name, bool invert = false)
    {
        if (func.Invoke(source) != invert)
            throw new ArgumentException(func.Method.Name + " check failed, inverted:" + invert, name);
    }

which I am using in following fashion

name.ThrowIf(String.IsNullOrEmpty, "name");
path.ThrowIf(File.Exists, "path", true);

Is there a neater solution to include the inverting functionality than passing the flag in my ThrowIf or creating a ThrowIfNot?


Solution

  • I believe that clearly another method would be more meaningful (as you've already said in your question...):

    name.ThrowIf(String.IsNullOrEmpty, "name");
    path.ThrowIfNot(File.Exists, "path");
    

    ...and you could just make your ThrowIf with the invert true/false parameter private:

    private static void ThrowIf<T>(this T source, Func<T,bool> func, string name, bool invert)
    {
        if (func.Invoke(source) != invert)
            throw new ArgumentException(func.Method.Name + " check failed, inverted:" + invert, name);
    }
    
    public static void ThrowIf<T>(this T source, Func<T, bool> func, string name) 
           => ThrowIf<T>(source, func, name, false);
    public static void ThrowIfNot<T>(this T source, Func<T, bool> func, string name) 
           => ThrowIf<T>(source, func, name, true);
    

    BTW, maybe it's better that you refactor everything to use code contracts if you're looking for implementing parameter validation:

    public void SomeMethod(string someParameter)
    {
        Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(someParameter));
    }