I came across a ASP.Net MVC project and came across an interesting property ViewBag. ViewBas is an interesting property where we can add as many properties to it as we want at run time. When I saw the source code of it, it is declare dynamic that explains it. I tried to do the same thing in my simple project, but stuck with how to initialize dynamic variable. I came across EpandoObject that is for exactly same reason.
ExpandoObject implements lots of interface such as IDictionary, ICollection, IEnumerabl, and INotifyPropertyChanged. Perhaps the most interesting one is IDynamicMetaObjectProvider. This interface has only one method.
Let’s take a look at the example to use ExpandoObject. Here is a simple program to demonstrate this.
The output of this program is as expected the value of properties.
Let’s try to create our own dynamic object that does something similar. .Net already provides one class named DynamicObject exactly for this purpose. All we have to do is override TryGetMeber and TrySetMember method overloaded.
Let’s create our own dynamic object class.
We also added two additional methods in this class to give the number of properties and the name of the properties.
Here is a complete C# program to demonstrate this.