Posted on: October 23, 2011
I never really used the dynamic keyword in a real application. I did some tutorials but not much.
This week, I got a situation where I was getting from Silverlight a Json object that I did not want to create an object for.
1string response = HtmlPage.Window.Invoke("GetMyJson").ToString();2 MyObject data = (MyObject)JsonConvert.DeserializeObject(response);
But, I did not wanted to create the MyObject because it was just for transferring data; a simple DTO object. Instead, I used the dynamic keyword provided by .Net framework 4.0.
The dynamic keyword will be resolved in runtime and this give us the leverage to access property that might not exist. For example, "GetMyJson" function was returning a simple object with 2 properties "Abc" and "Def".
So, in the C# code, I simply called those properties from the dynamic object.
1string response = HtmlPage.Window.Invoke("GetMyJson").ToString();2dynamic data = JsonConvert.DeserializeObject(response);3string s1 = data.Abc;4string s2 = data.Def;
This is pretty useful for accessing quickly some data from Json object.