How to check if two values ​​are equal in C #? (Considering any type of value)

I have this code here which is designed to resolve any types 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 with an int pair, it doesn't behave very well.

 AreEqual(3, 3) // prints Not Equal 
+4
source share
5 answers

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 using generics ( IEquatable<T> support):

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

Just to emphasize the reason for the "strange" behavior, this is because when you throw an int object onto a box object. Two 3s are converted to objects, and then you no longer compare numbers, you compare links that will not be the same.

+4
source

To check if two values ​​of an object are equal, use this:

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

Since the normal == operator assumes that the object is a reference type (despite the fact that value types also come down from objects).

+3
source

Try:

 if (expectedValue.Equals(actualValue)) 

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

 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, of course, matches @mike nelson :

 if (Object.Equals(expectedValue, actualValue)) 

so pick up his answer.

+2
source
 if (expectedValue != null) { if (expectedValue.Equals(actualValue)) { // enter code here } } 
-3
source

All Articles