-2
I created a class called MyList<T>
, with the intention of reproducing the class List
, and I overwrote the method Equals
to compare your instance with another of the same class, as follows:
class MyList<T> {
// Código da classe...
public override bool Equals(object obj) {
if (obj is MyList<T>) {
return Equals(obj, this);
}
return false;
}
public static bool Equals(MyList<T> listA, MyList<T> listB) {
if (listA.Count != listB.Count) {
return false;
}
for (long i = 0; i < listA.Count; i++) {
if (!listA[i].Equals(listB[i])) {
return false;
}
}
return true;
}
}
The problem is that whenever I try to check if one list is equal to another, the instance method Equals()
enters an infinite loop and generates StackOverflowException
with the following traceback:
Stack overflow.
Repeat 35393 times:
--------------------------------
at MyList`1[[System.__Canon, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].Equals(System.Object)
at System.Object.Equals(System.Object, System.Object)
--------------------------------
at MyList`1[[System.__Canon, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].Equals(System.Object)
at TestCSharp.Program.Main(System.String[])
If I use only the static method Equals()
, passing the two instances of MyList<T>
, verification occurs normally. That said, I believe the problem lies in the instance method.
Console.WriteLine(MyList<string>.Equals(list, list2)); // Retorna true ou false
Console.WriteLine(list.Equals(list2)); // Stack Overflow
What am I doing wrong? Where is the cause of loop infinite?
Do you have any reason to be using
long
?List.Count
isint
...– Luiz Felipe
@Luizfelipe I know, but I wanted my property as
long
with the intention that my list may contain more.– JeanExtreme002