I have this dynamic variable by which I serialize a json string.
dynamic result = serializer.Deserialize<dynamic>(json);
From this I am fetching result["success"]
which resolves as Dictionary<string, object>
at runtime. I then applied the namespace System.Linq
so that I may call .First()
on the variable.
I wrote
KeyValuePair<string, object> temp = result["success"].First();
Then I got the error,
'System.Collections.Generic.Dictionary' does not contain a definition for 'First'
(But it does, with LINQ, right?) Now I changed the code like this.
KeyValuePair<string, object> temp =
((Dictionary<string, object>)result["success"]).First();
It ran without any glitches. So I thought it might be because of the dynamically resolved variable. Then I tried with a native property of Dictionary<TKey, TValue>
like this
var foo = result["success"].Keys;
This too ran without any glitches and it got me confused and hence this post.
What I understood is that dynamically resolved variables only accept native properties and needs typecasting for inherited properties.
My doubts are
P.S: Coding in C# 4.0
But it does, with LINQ, right?
No, it doesn't. There's an extension method on IEnumerable<T>
of First()
, but extension methods can't be called on dynamic
values in the "normal" way.
However, you can use it as a normal static method:
KeyValuePair<string, object> temp = Enumerable.First(result["success"]);
That will still be bound dynamically, mind you - whereas when you cast result["success"]
, after the cast everything is just statically typed.
See more on this question at Stackoverflow