views:

490

answers:

2

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++?

+1  A: 

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.

thealliedhacker
KeyValuPair is not an immutable type.
Aaron Fischer
This also worked, but I couldn't accept both so I voted you both up.
brian
Actually, it is immutable. Here's a post by the designer explaining why https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=90998
thealliedhacker
Switched to this as best answer because of the immutable citation
brian
+1  A: 

try

System::Collections::Generic::KeyValuePair< System::String^, System::String^>^ k = gcnew System::Collections::Generic::KeyValuePair< System::String^, System::String^>(gcnew System::String("foo") ,gcnew System::String("bar"))   ;
Aaron Fischer
This worked, but I'm confused as to why. Is KeyValuePair a value type?
brian