5

I have a function which takes two parameters and returns true if they are equal or false if they are not:

private bool isequal(object a, object b)
{
    if (a != null)
        return a.Equals(b);
    if (b != null)
        return b.Equals(a);
    //if (a == null && b == null)
        return true;
}

Now I want to extend this function. It should also return true if a and b are 2 equal numbers but of different type.

For example:

int a = 15;
double b = 15;
if (isequal(a,b)) //should be true; right now it's false
{ //...
}

I already found a similar question (with answer) best way to compare double and int but a and b could be any type of number or something else than numbers. How can I check if it a and b are numeric at all? I hope there is a better way than checking all existing numeric types of .net (Int32, Int16, Int64, UInt32, Double, Decimal, ...)

//update: I managed to write a method which works pretty well. However there might be some issues with numbers of the type decimal (have not tested it yet). But it works for every other numeric type (including high numbers of Int64 or UInt64). If anybody is interested: code for number equality

Community
  • 1
  • 1
Preli
  • 2,953
  • 10
  • 37
  • 50
  • I think you are attempting the impossible. How can you compare Int64.MaxValue with a float or double and expect to achieve equality. There's not enough precision available. – David Heffernan Aug 24 '11 at 20:32
  • I never expected this. Int64.MaxValue and some float value of course will never be equal. But I expect it to work correctly for all possible combinations (Int64.MaxValue != Int64.MaxValue-1 beeing one of them) – Preli Aug 24 '11 at 21:25

2 Answers2

5

You could use Double.TryParse on both a and b. It will handle int, long, etc.

private bool isequal(object a, object b)
{
    if (a == null || b == null)
        return (a == b);

    double da, db;
    if (Double.TryParse(a.ToString(), out da) && Double.TryParse(b.ToString(), out db))
        return YourIsDoubleEqualEnough(da, db);

    return false;
}
Sorskoot
  • 10,190
  • 6
  • 55
  • 98
Donald
  • 1,718
  • 10
  • 18
  • The Double.TryParse code will only be reached if a AND b are null which will lead to a NullReferenceException! – Preli Aug 24 '11 at 19:40
  • You're right. I changed the null check in the code above to reflect that. – Donald Aug 30 '11 at 17:56
0

try this

private bool isequal(object a, object b)
{
int c,d;
        if (int.TryParse(a.ToString(), out c) && int.TryParse(b.ToString(), out d))
        {
            if (c == d)
                return true;
        }
if (a != null)
    return a.Equals(b);
if (b != null)
    return b.Equals(a);
//if (a == null && b == null)
    return true;
}
Blazen
  • 312
  • 3
  • 17
  • This will produce a NullReferenceException if a or b are null (because of a.ToString()). It will not also not work if a is int and b is float or decimal. – Preli Aug 24 '11 at 19:47