Adding Dynamic Properties: ExpandoObject vs DynamicObject
Brian Lagunas Brian Lagunas
17.9K subscribers
18,220 views
534

 Published On Dec 6, 2021

In this video, I answer the question "how to add dynamic properties to objects in c#"

Adding dynamic properties to objects in C# is actually pretty easy. There are primarily two ways for adding dynamic properties to objects in C#. One way to add dynamic properties in C# is to use the ExpandoObject. The other way to add dynamic properties is to use a custom DynamicObject.

Adding dynamic properties to objects in C# with the ExpandoObject requires the use of the dynamic keyword in .NET. To create an ExpandoObject your code will look somethign like this:

dynamic expando = new ExpandoObject();

From here you can now start adding dynamic properties to the ExpandoObect:

expando.FirstName = "Brian";

However if you don't know the name of your dynamic properties until runtime, you'll need to cast the ExpandoObject into an IDictionary enable to add your dynamic properties.

Something like:

var dictionary = expando as IDictionary{string, object};
dictionary.Add("PropertyName", PropertyValue);

Another way to add dynamic properties to objects in c# i to create a custom DynamicObject. Simply create a new class that drives from DynamicObject and override the TryGetmember and TrySetMemeber methods.

Something like this:

class Dynamic : DynamicObject
{
internal Dictionary{string, object} _dictionary = new Dictionary{string, object}();

public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return _dictionary.TryGetValue(binder.Name, out result);
}

public override bool TrySetMember(SetMemberBinder binder, object value)
{
AddProperty(binder.Name, value);
return true;
}

public void AddProperty(string name, object value)
{
_dictionary[name] = value;
}
}

From here you can start adding customized methods and logic for how you are adding dynamic properties to your objects at runtime.

Towards the end of this video, we will demonstrate adding dynamic properties using both the ExpandoObject and the DynamicObject to convert a CSV file to JSON.

Be sure to watch my new Pluralsight course "Introduction to Prism for WPF":
📺 http://bit.ly/PrismForWpf

Sponsor Me on GitHub:
🙏🏼 http://bit.ly/SponsorBrianOnGitHub

Follow Me:
🐦 Twitter: http://bit.ly/BrianLagunasOnTwitter
📖 Blog: http://bit.ly/BrianLagunasBlog

00:00 - Intro
01:55 - Using the ExpandoObject
07:37 - Using the DynamicObject
14:33 - Convert CSV to JSON with ExpandoObject
21:40 - Convert CSV to JSON with DynamicObject
25:54 - Summary

show more

Share/Embed