a C++/Cli ref class and TryGetValue method of C# Dictionary class

  • Thread starter Thread starter h_schmieder
  • Start date Start date
H

h_schmieder

Guest
Hello,

I have a C# extension written in C++/CLI and C# code which uses this Extension.

in my C++/CLI code I have

using namespace System::Collections::Generic;
using namespace System::Runtime::InteropServices;

public ref class ElementInfo : Comparer<ElementInfo^>, IEqualityComparer<ElementInfo^> {
public:
long Identifier;
String^ Name;
size_t Position;
size_t NumberParents;
size_t NumberChildren;

ElementInfo() : Identifier(-1) {}
ElementInfo(String^ name) : Name(name), NumberParents(0), NumberChildren(0) {}

virtual int GetHashCode(ElementInfo^ x) {
return x->Identifier;
}

int GetHashCode() override {
return GetHashCode(this);
}

int Compare(ElementInfo^ x, ElementInfo^ y) override {
return x->Identifier.CompareTo(y->Identifier);
}

virtual bool Equals(ElementInfo^ x, ElementInfo^ y) {
return Compare(x, y) == 0;
}

virtual bool Equals(ElementInfo^ to) {
return Equals(this, to);
}

String^ ToString() override {
return Name;
}
};


And i the C# code I have

private readonly Dictionary<Object, int> mapObjectToIndex = new Dictionary<object, int>();


public virtual int GetObjectIndex(object model)
{
int index;
if (model != null && this.mapObjectToIndex.TryGetValue(model, out index)) {
return index;
}

return -1;
}



GetObjectIndex is called with an ElementInfo object.

I see that the GetHashCode mehod of ElementInfo is called, but none of the equals method nor the compare method.

when TryGetValue is exceuted.

TryGetValue returns false althoud the used ElementInfo object is in mapObjectToIndex.

What is missing in my C++/CLI code ?

tia

Hendrik

Continue reading...
 
Back
Top