Home > Net >  Dictionary<string,dynamic> behaves differently when used in function where built than when use
Dictionary<string,dynamic> behaves differently when used in function where built than when use

Time:11-04

Using debug in VS 2019 on Windows Server 2019. I'm loading a Dictionary<string, dynamic> in a function to be used throughout the program. When I extract the dynamic object (o) from the Dictionary (dictGen) in the function (LoadStuff), it works fine. However, when it returns from the function, I can't extract the value from the Dictionary and use it as an dynamic object the way I did in the function.

So, here's a short version of the function:

private void LoadStuff(ref Dictionary<string, dynamic> dictGen) 
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
dynamic o = serializer.Deserialize<dynamic>("{}");
o["matchField"] = "i";
o["newField"] = "language";
dictGen.Add("sub div", o);
o = null;
o = dictGen["sub div"];
// in Immediate Window, typing o["matchField"] Displays "i" 
}

Then in the calling function, the LoadStuff is called:

Dictionary<string, dynamic> dictGen = new Dictionary<string, dynamic>();
void LoadStuff(ref dictGen);

dynamic o = dictGen["sub div"]
// In Immediate window or in use, typing o["matchField"] gives following error:

"error CS0021: Cannot apply indexing with [] to an expression of type 'object'"

I've tried explicitly casting dictGen["sub div"] as dynamic, using foreach loops like:

foreach(dynamic obj in dictGen.Values)  // using obj["matchField"]
foreach(var key in dictGen.Keys) // obj = dictGen[key]
foreach (KeyValuePair<string, dynamic> ooo in dictGen) // dynamic obj = ooo.Value;

But same problem no matter which way I try it. So, what's different using the Dictionary in the function from using it when it returns? How do I get the value for obj["matchField"]?

CodePudding user response:

Well, I had hoped someone would have given me some ideas that would lead to a good answer but that didn't happen. So, I created a plain ole C# object and used that in the Dictionary rather than the dynamic. It worked fine in the real program so I'm going use that even though I would have really like to have found why the dynamic object behaved the way it did.

  • Related