Thursday, May 24, 2007

Getting contains to work for the Generic List

In .Net 2.0, Generics have been introduced. I won't try to explain them here. I will provide an idiots guide to getting the contains method on List<> to work. Generics are quite powerful. They allow us to get all the functionality of a List without writing nearly any code. Let pretend I have an object (class) called MyCustomObject as defined below. public class MyCustomObject { string Title; string Description; public override bool Equals(object obj) { if (obj is MyCustomObject) { MyCustomObject other = obj as MyCustomObject; if (other == null) { return false; } else { bool same = other.Title == Title && other.Description == Description; return same; } } else { return false; } } } As you can see I have implemented the Equals method to only return two objects to be equal if they are of the same type and the Title and Description are the same. I consider this to be an expected behavior, but .Net wants to compare references to the objects, not the data members. The problem shows up when you want to use MyCustomObject in a List of MyCustomObjects. To get all the benefits of a List in .Net and write no code we can use Generics. In this case the List<> is what we will use. public class MyCustomObjectList : List<MyCustomObject> { } That is it. To use the List you could do something like: MyCustomObject obj1 = new MyCustomObject(); obj1.Title = "Test1"; obj1.Description = "Desc 1"; MyCustomListObjectList list = new MyCustomObjectList(); list.add(obj1); MyCustomObject obj2 = new MyCustomObject(); obj2.Title = "Test1"; obj2.Description = "Desc 1"; bool containsItem = list.contains(obj2); Notice the two objects have the same values. If we did not implement the Equals() method in MyCustomObject containsItem would be false. Since we changed what equals means, containsItem is now true because the values of the objects are the same regardless of the object itself.

No comments: