I need to make my custom object work correctly in a Dictionary, List, etc... so that I can change properties of the object, and allow it to be resorted, and not orphaned.
The last time I attempted overriding GetHashCode(), I orphaned objects when I added the object to the dictionary, made a change to the object (which changed GetHashCode) which somehow caused Dictionary to not properly dispose of the object from memory.
Question
Can someone explain:
What interfaces and interfaces I need to override in TrustedEntityReference to concatenate
int
andTrustedEntity
work correctly in a sorted dictionary?What values must never change with regard to what is used in a .NET dictionary object, or else risking orphaning the object? (Example, changing the emitted hashcode of an object may cause GC issues with a dictionary)
Here is a current sample object that I'm working on.
namespace Model
{
public class TrustedEntity
{
public TrustedEntity()
{
this.BackTrustLink = new List<TrustedEntityReference>();
this.ForwardTrustLink = new List<TrustedEntityReference>();
}
public List<TrustedEntityReference> BackTrustLink { get; set; }
public string EntryName { get; set; }
public List<TrustedEntityReference> ForwardTrustLink { get; set; }
}
// This is the object I want to be treated as a "key" in the above List<T>
// I want a duplicate object exception to occur if a duplicate TrustedEntityReference is inserted into trustedEntity.BackTrustLink or trustedEntity.ForwardTrustLink
public class TrustedEntityReference
{
public int HierarchyDepth { get; set; }
public TrustedEntity TrustedEntity {get; set; }
}
}
No interface is required to use List or Dictionary
TKey cannot change (otherwise you will not be able to find the entry in the Dictionary since you will be looking for the wrong key).
Edit:
Looks like I missed the TKey type.
I expect this means TrustedEntityReference should implement the IEqualityComparer interface (though I would implement ICompariable at the same time).
You could also specifiy your own using the Dictionary(IEqualityComparer) Constructor.
It is essential that the methods in these interfaces always return the same value, even if the value of the object has changed.
http://msdn.microsoft.com/en-us/library/ms132072.aspx
Please let me know if you need more.