I wrote a small helper method contentsToArrayList. If I pass it an object which implements ICollection, it returns an ArrayList containing the same elements as the original object. If I pass it another object, it returns an ArrayList containing the object itself.
Now I want to test the method. My unit test looks like this (a bit abbreviated, I included more test cases):
//Arrange
int a = 1;
ArrayList aAsArrayList = new ArrayList();
aAsArrayList.Add(a);
List<int> f = new List<int>() { 4, 5, 6 };
ArrayList fAsArrayList = new ArrayList(f);
//Act
ArrayList aReturned = contentsToArrayList(a);
ArrayList fReturned = contentsToArrayList(f);
Now I am not sure how to write my asserts. Basically, I want to make sure that aAsArrayList contains the same object(s) as aReturned. But ArrayList being a reference type, I am not sure it has value equality defined. Can I just compare the arraylists easily, using something like aReturned == aAsArrayList, or do I have to compare each member of the arraylist?
I am not sure it has value equality defined.
You are correct, it does not have value equality defined.
One way to compare ArrayList
objects for equality is using LINQ:
if (aReturned.Cast<object>().SequenceEqual(fReturned.Cast<object>())) {
...
}
Casts to object
are the most "forgiving" - they would not trigger a cast exception in your tests. If you know that both arrays contain values of type int
, you can replace the type in the Cast<object>()
to Cast<int>()
.
A similar question about the C# specification
List<T> operator == In the C# Language Specification Version 4 on StackOverflow
Would imply that the answer to this question is no
Additionally the page
ArrayList on MSDN
Shows that the ArrayList object has no override for == operator
Thus you will probably write a helper method that checks that each element of one array is contained within the other. If this is true for both ArrayLists then they are equal in the way you desire. Something like
public bool ArrayListsEqual(ArrayList a, ArrayList b) {
foreach (obj A in a) {
if (!b.Contains(A)) {
return false;
}
}
foreach (obj B in b) {
if (!a.Contains(B)) {
return false;
}
}
return true;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.