Skip to main content
Home Forums Silverlight Programming Report a Silverlight Bug Collection methods not finding Strings within collection
2 replies. Latest Post by andrewjw on February 23, 2009.
(0)
andrewjw
Member
7 points
17 Posts
02-17-2009 5:12 PM |
In my application, the Items collection of a listbox is being filled with string values. At a later time, the application attempts to use other methods (Contains, IndexOf, Remove) to perform operations on the collection, but these wrongly report that the string value is not present in the listbox when it is.
(I am guessing that internally these methods use == to check equality rather than .Equals, with the result that they only identify strings as being present within the listbox if the string objects themselves are identical rather than if their string values are equal.)
Some example code showing the problem:
string a = new string(new char[] { 'h', 'e', 'l', 'l', 'o' });string b = new string(new char[] { 'h', 'e', 'l', 'l', 'o' }); // a and b are unique string objects with identical valueslistbox.Items.Add(a);listbox.Items.Remove(b); // This fails to remove 'hello' from the listbox
bryant
Star
9937 points
1,629 Posts
02-17-2009 6:04 PM |
A better option would be to use an observable collection and just perform the add/remove on that.
var strings = new ObservableCollection<string>() {"hello","goodbye"}; listbox.ItemsSource = strings; strings.Remove("hello");
02-23-2009 3:15 PM |
Hmmm, it's interesting to see that ObservableCollection doesn't seem to suffer from the same bug... its implementation must be different.
That's a good work-around bryant. Unfortunately for complicated reasons I can't use it, but obviously I can implement a simple work-around by writing my own custom .Contains, .IndexOf, and .Remove methods, which I can use until the bug is fixed.