C# compare two objects of unknown types (including reference and value types)

You can use the static object.Equals(object x, object y) method and not bother writing your method at all. That will handle nulls appropriately, and delegate to an implementation of object.Equals(object) associated with either x or y… it shouldn’t matter which, as Equals is meant to be symmetric.

Note that this doesn’t use the == operators for any type – operators can’t be overridden, only overloaded (which means they’re chosen at compile-time, not execution-time. In most cases Equals should do what you want. In some cases, == may not be overloaded even though Equals is overridden… but I’ve never known the reverse to be true in any types I’ve worked with.

Note that using this approach will box any value types…

EDIT: Removed section about effectively reimplementing – poorly – EqualityComparer<T>.Default. See Marc’s answer for more. This won’t help you if you can’t use a generic type, of course.

One final point: I wouldn’t call your method Compare. That name is usually associated with ordering values rather than comparing them for equality.

Leave a Comment

tech