Search code examples
.netgenericsvisual-c++.net-2.0managed-c++

Creating a KeyValuePair in Managed C++


I have yet another managed C++ KeyValuePair question where I know what to do in C#, but am having a hard time translating to managed C++. Here is the code that does what I want to do in C#:

KeyValuePair<String, String> KVP = new KeyValuePair<string, string>("this", "that");

I've reflected it into MC++ and get this:

KeyValuePair<String __gc*, String __gc*> __gc* KVP = (S"this", S"that");

which I'm translating to:

KeyValuePair<String ^, String ^> KVP = (gcnew String("this"), gcnew String("that"));

I know from my previous question that KeyValuePair is a value type; is the problem that it's a value type in C++ and a reference type in C#? Can anyone tell me how to set the key and value of a KeyValuePair from C++?


Solution

  • This should do it:

    KeyValuePair< String ^, String ^> k(gcnew String("Foo"), gcnew String("Bar"));

    KeyValuePair is an immutable type, so you have to pass everything to the constructor, which looks the same as in C#, except you write it like this if the object is on the stack.