.net - C# compare two objects of unknown types (including reference and value types) -
is possible in c# compare 2 objects of unknown types, (including both reference , value types) using type comparators if exist?
the goal write function have signature this:
public bool compare(object a, object b) { // compare logic goes here }
which return
compare(100d, 100d) == true compare(100f, 100f) == true compare("hello", "hello") == true compare(null, null) == true compare(100d, 101d) == false compare(100f, null) == false // use type comparators possible, i.e.: compare(new datetime(2010, 12, 01), new datetime(2010, 12, 01)) == true compare(new datetime(2010, 12, 01), new datetime(2010, 12, 02)) == false compare(new datetime(2010, 12, 01), null) == false
is there generic approach solving problem work type of object?
you can use static object.equals(object x, object y)
method , not bother writing method @ all. handle nulls appropriately, , delegate implementation of object.equals(object)
associated either x
or y
... shouldn't matter which, equals
meant symmetric.
note doesn't use == operators type - operators can't overridden, overloaded (which means they're chosen @ compile-time, not execution-time. in cases equals
should want. in cases, == may not overloaded though equals
overridden... i've never known reverse true in types i've worked with.
note using approach box value types...
edit: removed section reimplementing - poorly - equalitycomparer<t>.default
. see marc's answer more. won't if can't use generic type, of course.
one final point: wouldn't call method compare
. name associated ordering values rather comparing them equality.
Comments
Post a Comment