IComparable IgnoreCase

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>

preguntado el 22 de mayo de 12 a las 20:05

Would not it work for you to simply handle the string case by testing the type of T? Something like if(typeof(T)==string) String.Compare(...) -

Yes, this was what I was looking for. Didn't realize how the type comparisom was done. Thanks! -

2 Respuestas

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.

contestado el 22 de mayo de 12 a las 20:05

Puede probar:

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");
        }
    }

contestado el 22 de mayo de 12 a las 20:05

This worked great - did not know it was possible to get the type of the generic. Thanks! - Sperry

You're welcome! It's possible using reflection, if you want to learn more, check este - Luis

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.