I have a situation where I would like to do something simular to what was done with the ASP.NET MVC 3 ViewBag object where properties are created at runtime? Or is it at compile time?
Anyway I was wondering how to go about creating an object with this behaviour?
Behavior wise the ViewBag acts pretty much like ExpandoObject so that maybe what you want to use. However if you want to do custom behaviors you can subclass DynamicObject. The dynamic keyword is important when using these kinds of objects in that it tells to compiler to bind the method calls at runtime rather than compile time, however the dynamic keyword on a plain old clr type will just avoid type checking and won't give your object dynamic implementation type features that is what ExpandoObject or DynamicObject are for.
I think you want an anonymous type. See http://msdn.microsoft.com/en-us/library/bb397696.aspx
For example:
Then you can just get properties as in normal C#
Use an object of type
dynamic
. See this article for more information.ViewBag
is declared like this:I created something like this:
then you can use it like this:
note that entry for "JAJA" was never created ... and still doesn't throw an exception, just returns null
hope this helps somebody