Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Compare two object values

Tags:

c#

.net

I currently have two objects (of the same type) that may represent any primitive value such as string, int, datetime etc.

var valueX = ...;
var valueY = ...;

Atm I compare them on string level like this

var result = string.Compare(fieldValueX.ToString(), fieldValueY.ToString(), StringComparison.Ordinal);

But I need to compare them on type level (as ints if those happen to be ints

int i = 0;
int j = 2;
i.CompareTo(j);

, as dates if they happen to be date etc), something like

object.Compare(x,y);

That returns -1,0,1 in the same way. What are the ways to achieve that ?

like image 608
eXPerience Avatar asked Nov 21 '25 08:11

eXPerience


2 Answers

Thanks for your answers, the correct way was to check if the object implements IComparable and if it does - make a typecast and call CompareTo

if (valueX is IComparable)
{
     var compareResult = ((IComparable)valueX).CompareTo((IComparable)valueY);
}
like image 163
eXPerience Avatar answered Nov 22 '25 23:11

eXPerience


Object1.Equals(obj1, obj2) wont work unless @object is referencing the same object.

EG:

var obj1 = new MyObject();
var obj2 = new MyObject();

This will return "False" for Object1.Equals(obj1, obj2) as they are different ref's

var obj1 = new MyObject();
var obj2 = obj1;

This will return "True" for Object1.Equals(obj1, obj2) as they are the same ref.

Solution: You will most likely need to write an extension method that overrides Object.Equals. either create a custom object comparer for a specific type (See here for custom object comparer:) or you can dynamically go through each property and compare.

like image 39
Tristan van Dam Avatar answered Nov 22 '25 23:11

Tristan van Dam