Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

types

equals

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
like image 542
mike nelson Avatar asked Nov 30 '22 07:11

mike nelson


1 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 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");
    }
}
like image 174
Marc Gravell Avatar answered Dec 04 '22 01:12

Marc Gravell