I want to know how can I compare two objects (which is of the same class) like the string.Compare()
method.
Is there any way to do this?
You can implement IComparable
interface, like sugested here:
public class Temperature : IComparable
{
// The temperature value
protected double temperatureF;
public int CompareTo(object obj) {
if (obj == null) return 1;
Temperature otherTemperature = obj as Temperature;
if (otherTemperature != null)
return this.temperatureF.CompareTo(otherTemperature.temperatureF);
else
throw new ArgumentException("Object is not a Temperature");
}
...
source
You will have CompareTo
method which will compare items of your class. More on IComparable
can be found here on SO. Having CompareTo
you can sort lists of your objects according to comparision function like mentioned here
since objects are reference types, so you should use obj.Equals() method. also note that:
string.ReferenceEquals(str, str2);
It obviously compares references.
str.Equals(str2)
Tries to compare references at first. Then it tries to compare by value.
str == str2
Does the same as Equals.
You need to implement the IComparable interface.
private class sortYearAscendingHelper : IComparer
{
int IComparer.Compare(object a, object b)
{
car c1=(car)a;
car c2=(car)b;
if (c1.year > c2.year)
return 1;
if (c1.year < c2.year)
return -1;
else
return 0;
}
}
Original post can be found Here
You can check two equality Reference Equality and Value Equality
Reference equality
Reference equality means that two object references refer to the same underlying object. This can occur through simple assignment, as shown in the following example.
class Test
{
public int Num { get; set; }
public string Str { get; set; }
static void Main()
{
Test a = new Test() { Num = 1, Str = "Hi" };
Test b = new Test() { Num = 1, Str = "Hi" };
bool areEqual = System.Object.ReferenceEquals(a, b);
// Output will be false
System.Console.WriteLine("ReferenceEquals(a, b) = {0}", areEqual);
// Assign b to a.
b = a;
// Repeat calls with different results.
areEqual = System.Object.ReferenceEquals(a, b);
// Output will be true
System.Console.WriteLine("ReferenceEquals(a, b) = {0}", areEqual);
}
}
Value equality
Value equality means that two objects contain the same value or values. For primitive value types such as int or bool, tests for value equality are straightforward.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With