mike nelson
mike nelson

Reputation: 22136

How can I check if two values in c# are equal? (Given any type of value)

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

Upvotes: 4

Views: 6335

Answers (5)

Jean Azzopardi
Jean Azzopardi

Reputation: 2289

if (expectedValue != null)
{
    if (expectedValue.Equals(actualValue))
    {
        // enter code here
    }
}

Upvotes: -3

Peter Lillevold
Peter Lillevold

Reputation: 33920

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.

Upvotes: 4

mike nelson
mike nelson

Reputation: 22136

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).

Upvotes: 3

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391306

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.

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1062600

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

Upvotes: 16

Related Questions