ZuluAlphaCharlie
ZuluAlphaCharlie

Reputation: 287

Generic Method That Inverts Booleans

I have a method with a generic parameter that filters values based on runtime string values. It either lets the value through or returns the default();

public T Filter<T>(string target, string actual, T value)
    {
        bool isMatch = !string.IsNullOrEmpty(target)
            && !string.IsNullOrEmpty(actual)
            && target.ToUpper() == actual.ToUpper();


        return isMatch ? value : default(T);

    }

This works fine for most everything except booleans. When a boolean false comes in and should be filtered, it comes back out as false -- the default() for boolean.

So what I want this to do when a bool is passed in is to return the inverse of the boolean. How to get from T to bool and back into the return type T?

Thanks!

Upvotes: 1

Views: 143

Answers (3)

jdphenix
jdphenix

Reputation: 15425

Edit: I would use dtb's answer with default parameters. However, if you were for whatever reason unable to use it, here is my alternative.

I would refactor the matching code to a new method and overload the generic with a specific version for boolean values.

    public T Filter<T>(string target, string actual, T value)
    {
        return _match(target, actual) ? value : default(T);
    }

    public bool Filter(string target, string actual, bool value) 
    { 
        return _match(target, actual) ? value : !value;
    }

    private bool _match(string target, string actual)
    { 
        return !string.IsNullOrEmpty(target)
            && !string.IsNullOrEmpty(actual)
            && string.Equals(target, actual, StringComparison.CurrentCultureIgnoreCase);
    }

When the 3rd parameter is boolean, the method call will resolve to the boolean version. When it isn't, it will resolve to the generic version.

Upvotes: 2

dtb
dtb

Reputation: 217293

Have you considered passing the default value to be returned to the method?

public T Filter<T>(string target, string actual, T value, T defaultValue = default(T))
{
    bool isMatch = !string.IsNullOrEmpty(target)
        && !string.IsNullOrEmpty(actual)
        && string.Equals(target, actual, StringComparison.CurrentCultureIgnoreCase)

    return isMatch ? value : defaultValue;
}

Usage:

Filter("foo", "bar", 42);          // returns 0
Filter("foo", "bar", false, true); // returns true

Upvotes: 2

siride
siride

Reputation: 209585

You could make this easier by using bool? as your generic type. When there's no match, default(bool?) will be null, which is quite distinguishable from true or false. This will also work for other primitive and values types, which will return null instead of a perfectly valid 0.

Upvotes: 2

Related Questions