Hi,
I'm trying to use a generics dictionary with a key class that implements and
needs IComparable<>.
However when I attempt to use the dictionary, it doesn't appear to use the
IComparable<> to find the key.
In the example below, accessing the dictionary by using the exact key object
that was used to add to the dictionary works.
(see code comment 1).
However, if I attempt to access the dictionary by using a key object that
was newly created, but one that does satisfy the IComparable<> condition,
then I get a "The given key was not present in the dictionary." exception.
(see code comment 2).
Am I reading this wrong, or should this really work?
Is there something that I'm doing wrong?
According to help:
"Generic Dictionary requires a comparer implementation to perform
comparisons. The default comparer Generic
System.Collections.Generic.Comparer.Default checks whether the key type K
implements Generic System.IComparable and uses that implementation, if
available. If not, Generic System.Collections.Generic.Comparer.Default
checks whether the key type K implements System.IComparable. If the key type
K does not implement either interface, you can specify a Generic
System.Collections.Generic.IComparer implementation in a constructor
overload that accepts a comparer parameter."
When I query executeTable.Comparer, it returns this:
{System.Collections.Generic.ObjectEqualityComparer <Test.OperationEntityType>
}
[System.Collections.Generic.ObjectEqualityComparer< Test.OperationEntityType>
]:
{System.Collections.Generic.ObjectEqualityComparer <Test.OperationEntityType>
}
FYI, I'm using VS 2005 Beta 2.
Thanks,
Erik
_________________________________
using System;
using System.Collections.Generic;
using System.Text;
namespace Test
{
public class OperationEntityType : IComparable<OperationEntityType>
{
public int m_operationId;
public Type m_entityType;
public OperationEntityType(int aOperationId, Type aEntityType)
{
m_operationId = aOperationId;
m_entityType = aEntityType;
}
public int CompareTo(OperationEntityType other)
{
if ((other.m_operationId == m_operationId)
&& (other.m_entityType == m_entityType))
return 0;
else
return 1;
}
public bool Equals(OperationEntityType other)
{
return (CompareTo(other) == 0);
}
}
public delegate object OperationExecuteDelegate(object aContext);
public class Class1
{
public static object OnExecute(object aContext)
{
Dictionary<OperationEntityType,
OperationExecuteDelegate> executeTable =
new Dictionary<OperationEntityType,
OperationExecuteDelegate>();
OperationEntityType m_firstOperation = new
OperationEntityType(1,
typeof(string));
executeTable.Add(m_firstOperation,
null);
OperationExecuteDelegate execute;
// 1) This works.
execute = executeTable[m_firstOperation];
// 2) This produces a "The given key was not present in the dictionary."
exception.
execute = executeTable[new OperationEntityType(1,
typeof(string))];
return execute(aContext);
}
public static void Main()
{
OnExecute(null);
}
}
}