It's syntactic sugar, basically. I don't think it's meant to be functionally "better" than the old ViewData
dictionary, just a lot less verbose to work with. Instead of taking things out of the dictionary and manually casting them (and crashing if they're wrong), you can just use them without any extra verbiage (and crash if they're wrong).
Here is a blog post which has some "before and after" code samples using the old ViewData
dictionary and the new ViewBag
dynamic. In particular, see the foreach
iterating through the list of strings.
foreach (var color in ViewData["listColors"] as List<string>)
..becomes..
foreach (var color in ViewBag.ListColors)
Edit: Martinho makes an excellent point! The new version should probably explicitly declare a string
rather than a var
, like so:
foreach (string color in ViewBag.ListColors)
Two reasons:
- If you've gotten it wrong, e.g.
ViewBag.ListColors
is a List
of System.Drawing.Color
objects, you'll get an immediate and clear error, Cannot convert type 'System.Drawing.Color' to 'string'
, rather than weird and undesired output.
- If you declare
color
as a var
, the type inference will infer it as a dynamic
, thus all the usage of it in the loop will go through the Dynamic Language Runtime's late binding, right? Surely this is an unnecessary performance hit?