Search code examples
c#shorthandor-operator

Possible shorthand solution for OR operator issue


I tried to come up with a shorthand solution for an or operator. So I came up with something like this, but the result is always false.

Can someone give some advice on how can I fix this issue? Will this even work at all? If not, are there any other solutions similar to this?

P.S. I know that this question has been asked before, but unfortunately, none of the solutions suited my needs.

The code:

public static bool IsEqualsTo(object o, params object[] p)
{
    for (int i = 0; i < p.Length; i++)
    {
        if (o == p[i])
        { return true; }
    }
    return false;
}

So for example:

From if (MovementState == PMovementState.Walking || MovementState == PMovementState.Idle)

to if (IsEqualsTo(MovementState, PMovementState.Walking, PMovementState.Idle))

or

From if (input.text == "text" || input.text == "text2" || input.text == "text3")

to if (IsEqualsTo(input.text, "text", "text2", "text3"))


Solution

  • You could use a generic version to avoid boxing/unboxing:

    public static bool IsEqualsTo<T>(T o, params T[] p)
    {
        var comparer = EqualityComparer<T>.Default; // make it an optional parameter
        for (int i = 0; i < p.Length; i++)
        {
            if (comparer.Equals(o, p[i]))
                return true;
        }
        return false;
    }
    

    The reason for your issue is that the Object parameter is boxed if a value type like an enum(struct) is passed. This will cause == to return false because it's not the same reference. Use Equals as shown above to fix this issue and use generics to make it more efficient.

    As noted you can also shorten the body of the method with LINQ:

    return p.Contains(o, comparer);