Question

I have a method which returns an object, which could be one of a number of different data types, including strings, numbers and bools; and at some point I need to compare the equality of two values returned from this method. I'm using == instead of Equals() because I need different number types to compare - ie. 3 == 3.0 - which is working fine for strings and numbers, but for some reason it falls down when I'm comparing boolean values.

What would be the best way to solve this problem? I'd prefer not to have to detect the type and cast if bool, but I will do if there is no other solution

My code looks something like:

private object GetValue() {
    // does some stuff, returns either a boolean, string or number value
}

var value1 = GetValue();
var value2 = GetValue();
if (value1 == value2) {
    // do something
}
Was it helpful?

Solution

public bool Compare(object value1, object value2)
{
    if (value1.GetType() == value2.GetType())
    {
        return value1.Equals(value2);
    }
    else
    {
        //your logic for handling different numbers
    }
}

OTHER TIPS

How about make your function to return string and then just parse the result to bool or int or whatever you want and then compare?

EDIT:

private string GetValue() {}

string val = getValue();
string val2 = getValue();

bool a1;
bool b1;
int a2;
int b2;
double;
double;

bool r1 = bool.TryParse(val, out a1);
bool r2 = bool.TryParse(val2, out b1);
bool r3 = int.TryParse(val, out a2);
bool r4 = int.TryParse(val2, out b2);
bool r5 = double.TryParse(val, out a3);
bool r6 = double.TryParse(val2, out b3);

if ((a1 == b1 && r1 && r2)) || (a2 == b2 && r3 && r4)) || (a3 == b3 && r5 && r6))
return true;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top