I have a list (to be precise ImmutableHashSet<ListItem> of System.Collections.Immutable) of the base elements and try calling the following code
_baseList.Contains(derivedItem)
but it returns false .
Even if the following lines of code return true
object.ReferenceEquals(_baseList.First(), derivedItem) object.Equals(_baseList.First(), derivedItem) _baseList.First().GetHashCode() == derivedItem.GetHashCode()
I can even write the following and it returns true:
_baseList.OfType<DerivedClass>().Contains(derivedItem)
What I am doing wrong, I would like not to write .OfType stuff.
Edit:
private ImmutableHashSet<BaseClass> _baseList; public class BaseClass { } public class DerivedClass : BaseClass { } public void DoStuff() { var items = _baseList.OfType<DerivedClass>().ToList(); foreach (var derivedItem in items) { RemoveItem(derivedItem); } } public void RemoveItem(BaseClass derivedItem) { if (_baseList.Contains(derivedItem)) {
Edit2:
Here, the reproduced code of my problem is similar to ImmutableHashSet<> caches GetHashCode and does not compare the current GetHashCode with the entries inside the list, is there a way to tell ImmutableHashSet<> that the GetHashCode elements can be different, at least for the element I'm checking now, so how is he his damn link ...
namespace ConsoleApplication1 { class Program { private static ImmutableHashSet<BaseClass> _baseList; static void Main(string[] args) { _baseList = ImmutableHashSet.Create<BaseClass>(); _baseList = _baseList.Add(new DerivedClass("B1")); _baseList = _baseList.Add(new DerivedClass("B2")); _baseList = _baseList.Add(new DerivedClass("B3")); _baseList = _baseList.Add(new DerivedClass("B4")); _baseList = _baseList.Add(new DerivedClass("B5")); DoStuff(); Console.WriteLine(_baseList.Count);
If I changed the value of ImmutableHashSet<> to ImmutableList<> , the code would work just fine, so if you guys havenβt come up with any good idea, I will switch to the list.