Question

I have this code here, which is intended to allow any type of arguments:

public static void AreEqual(object expectedValue, object actualValue) {
    if (expectedValue == actualValue) {
        HttpContext.Current.Response.Write("Equal");
    } else {
        HttpContext.Current.Response.Write("Not Equal");
    }
}

If I call it using a couple of ints it does not behave very well.

AreEqual(3, 3)   // prints Not Equal
Was it helpful?

Solution

At the simplest level:

public static void AreEqual(object expectedValue, object actualValue) {
    if (object.Equals(expectedValue,actualValue)) {
            HttpContext.Current.Response.Write("Equal");
    } else {
            HttpContext.Current.Response.Write("Not Equal");
    }
}

Or with generics (supports IEquatable<T>):

public static void AreEqual<T>(T expectedValue, T actualValue) {
    if (EqualityComparer<T>.Default.Equals(expectedValue,actualValue)) {
            HttpContext.Current.Response.Write("Equal");
    } else {
            HttpContext.Current.Response.Write("Not Equal");
    }
}

OTHER TIPS

Just to highlight the reason for the "strange" behavior is because when you cast an int to object boxing occurs. The two 3s are converted to objects and then you are not comparing numbers anymore, you are comparing references, which will not be the same.

To check if the two object values are equal use this:

if (Object.Equals(expectedValue, actualValue)) {

As the normal == operator assumes an object is a reference type (despite the fact that value types also descend from objects).

Try:

if (expectedValue.Equals(actualValue))

and of course you need to handle null, so you should try this:

Boolean eq = false;
if (expectedValue == null || actualValue == null)
    eq = (expectedValue == actualValue);
else
    eq = expectedValue.Equals(actualValue);

if (eq) {
    HttpContext.Current.Response.Write("Equal");
} else {
    HttpContext.Current.Response.Write("Not Equal");
}

This is of course the same as @mike nelson's answer:

if (Object.Equals(expectedValue, actualValue))

so go upvote his answer.

if (expectedValue != null)
{
    if (expectedValue.Equals(actualValue))
    {
        // enter code here
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top