IComparable IgnoreCase

457 Views Asked by At

I'm writing a function to compare 2 values of IComparable type, and throwing if not equal. Basically, re-making assert. Yes, I'm aware I'm reinventing the wheel.

    public static void IsEqual<T>(T Value1, T Value2) where T : IComparable<T>
    {
        if (0 != Value1.CompareTo(Value2))
        {
            throw new ApplicationException("Fail");
        }
    }

Works fine except for strings, I was hoping for the option of ignoring case. "AA" vs "aa"

I'd like to override this method specifically when T is a String, so I could use String.Compare and ignore case. It would also be cool to have another param so the user could specify if string should be ignored (though, this is useless for other types like int so seems kind of like a confusing/bad design. I'm open to suggestions here).

Is there a good way to do this? I'm also open to changing to a different type than IComparable, initially thought this was the best interface for the job but now realize I could have been wrong.

where T : IComparable<T>
2

There are 2 best solutions below

2
On BEST ANSWER

You can try:

public static void IsEqual<T>(T Value1, T Value2) where T : IComparable<T>
    {
        if (typeof(T) == typeof(String))
        {
            if (String.Compare(Value1.ToString(), Value2.ToString(), true) != 0)
            {
                throw new ApplicationException("Fail");
            }
        }
        else if (0 != Value1.CompareTo(Value2))
        {
            throw new ApplicationException("Fail");
        }
    }
0
On

You could create another function, specially for strings.

public static void IsEqual(string value1, string value2) 
{
  if (string.Compare(value1, value2, true) != 0)
    throw new ApplicationException("Fail for strings");
}

Then if you would call IsEqual(1, 1) your generic overload will be called, but if you call IsEqual("A", "a") the string overload will be called. Then you can simply add another optional parameter for the string overload, if desired.