Adding Dynamic Properties: ExpandoObject vs DynamicObject
HTML-код
- Опубликовано: 12 июн 2024
- 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":
📺 bit.ly/PrismForWpf
Sponsor Me on GitHub:
🙏🏼 bit.ly/SponsorBrianOnGitHub
Follow Me:
🐦 Twitter: bit.ly/BrianLagunasOnTwitter
📖 Blog: 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 - Наука
Thank you for this video.. You explained everything so clearly.
Thank you very much.
One word, Amazing, I don't have something else that can describe all of this(Experience, Explanations, clarity)
Thank you so much
Great topic, very clearly explained. You have a new subscriber here!
Thank you very much
Very helpful and well worded. Ty!
You are so welcome!
Thank you very much for your explanations which are very clear. It's really good work 😃 Thanks to you, it is much simpler to manipulate objects in my development project. 👍👏
Fantastic video Brian :) Quite a lot covered there and with a great real world example. I have to use dynamic objects a lot but from xml lol
Thank you very much
Fantastic, you saved me. Thanks a ton!
Thanks for watching
Fantastic, Saved my day
Great to hear.
great tutorial!!!!
Your're awesome! Thank you
Thank you for the kind words
Amazing thanks you so much, greetings from Paraguay
Thank you for watching
Hi Brian! Very good explanation bro thank you!
Thank you for the comment
Great topic, thanks.
Thanks for watching
Great, thank you very much!
Thanks for watching
@@BrianLagunas I have a problem. I have such a dynamic object, and I store a List of other dynamic objects in the _dictionary. That means, the Lists Key is called "Details" and the Value of this is a List with 20 _dictionarys. Now I try to access the Keys and Values of the 20 _dictionarys to write it as a Json string, but I struggle. Maybe you can help?
Hell yeah this is exactly what I was looking for! I've been trying to build a dynamic blazor component to perform CRUD operations on data and could not wrap my head around the dynamic typing. Especially referencing the property when you have the property name as a string. This helped me so much, amazing tutorial
Thank you so much. I’m glad I could be helpful
This kind of stuff I need.
Glad you enjoyed it!
Hi Brian This is really informative.
Thanks for watching
Thanks alot... Your video saved me 😇
Yay! Great to hear
Hi Brian, can you make a video on how to implement a paging collection view in your approach?
Thanks!
Great explanation. Just a quick question, performance wise which is better Dynamic object or ExpandoObject when dealing with large data?
Really cool
Thanks for watching
I love JObject, JArray, and JToken from NewtownSoft
The best way to go for me too. I like the tutorial about how to use ExpandoObject though.
Thanks for that. I'm exploring options for handling a similar use case. I think I can go down this route but I wonder if I may come unstuck somewhere, specially as you showed how there was some custom code that was needed around serialization.
I have two use cases for reading into this dynamic object list.
1) data coming in from database (as xml) - i need to convert this xml into dynamic class (each xml attribute becomes a property in the dynamic object)
2) data read from html form via javascript and sent to c# as a dictionary (where it needs to be read into the dynamic object)
For case #1, in my current implementation (where I don't use dynamic object but a simple
Class with a bunch of properties already defined against the class), I read xml into class using reflection. I then pass this class around to front end as serialized json. When I want to bind this data into UI, I would turn it back into that class object on the server and read properties out
I suppose this is not easy to digest and give direction, but I wonder if this sounds like a good case for using dynamic?
This sounds like a great use of dynamic
I miss this videos Brian
hope u r well
All is well. It’s just really hard to find time to record videos.
Ok, Brian, Useful and great as usual, but I have a question, why don't I use the dictionary itself directly and use its indexer instead? Is there like a performance adv. for dynamic and expando obj? Because under yhe hood they are actually a dictionary of string and object key pairs
Don’t get caught up on the specific Csv parsing example. This video was meant to demonstrate how ExpandoObject and DynamicObject works and things you have to consider when using them.
Was very helpful thanks
Thanks for watching
I have a qustion, I'm using Ihost, and I'm adding both ViewModel and Interface of View as Transient, now I need to be able to get the current/active view which assostaed with the Interface, however, if I tried to use GetService it will return new Iview which is not the current active one.
How I can solve that, or in otherworld, How I get all active instance of type Iview?
Basicly All I need is haveing single Iview eachtime I have Iview shown as a Dialog, after it close I get need a new instance of Iview. and ViewModel .
Thanks!
Very Good. But, how can i use DynamicObject for display in PropertyGrid(windows form) and change value? With [Category, DisplayName and so on]? Thanks
Hi Brian, great video! thanks. I've got an issue where I'm binding a dynamic collection to a DataGrid and letting the grid auto discover the columns, the only issue I'm having is with the type discovery as all the column Types will be of type object. So Booleans will show the ToString() "True" / "False" rather than a checkbox. Is it somehow possible to strongly type the properties at runtime?
You could build the columns dynamically instead of letting the grid auto discover.
What are the benefits of using expando object over dataset?
Good guide, thank you. But is not it easier to use just dictionary directly? It allows you to use your favorite syntax and it is serializable as well.
Dictionary does not do the same things as ExpandoObject or DynamicObject.
i have property name and datatypes in SQL Data Table. I want to create class properties using the Data Table values. How can i do that sir?
Excellent video explaining dynamic/ExpandoObject. I have an interesting and challenging problem. How do you view dynamic objects in a DataGrid? Object properties (columns) and row count can change at runtime and are not known at compile time. I haven't been successful with an ObservableCollection. How would you tackle this problem? Thanks!
You should be able to use an ObservableCollection and then let your grid auto discover the columns, the only issue you will have is with the type discovery as all the column Types will be of type object. So Booleans will show the ToString() "True" / "False" rather than a checkbox. This is the bit I'm struggling to figure out how to do...
This is really clever for data that doesn't need to bind to anything, but I'm not sure how useful it is when you need to start binding those dynamic data properties to UI elements. I was initially thinking it could be used for an API response to hold various data elements in a "Data" wrapper. You'd then just loop thru that Data wrapper and add each property name and value to your dataObjects list. That's great up to that point, but how would you connect up a UI binding at that point w/o knowing the dynamic property names beforehand, and what happens if those change in the underlying API Data wrapper?
You can dynamically create bindings in code too, plus ExpandoObject implements INotifyPropertyChanged as well 😁
Hi ! This video is brilliant!! Thanks ! however , in my case I have a windows form drag and drop file application that in the left hand I drop an old xml file and in the right hand the new one . once I does it I hit the compare button to create a new file with the same values but with adding some missing properties from the new one.. for now I'm using a serialize with static serializable class my question is : how can I do it with dynamic object (consider the fact that some xml files contains changes in their hierarchy) .. and don't count on pre defined class?
This is the type of question I get paid to answer 😁
@@BrianLagunas thanks ..
This is an awesome video, could you maybe make an example on how to use Azure Cosmos DB with it?
Hmmmm. I don’t use Azure much but maybe I can do something in the future.
@@BrianLagunas Thanks for answering. Don't must be Azure. I am interested about in adding dynamic props and saving them into a database and moreover query them. Often there is a business case where they wanna add a custom property and filter for it. Usually I do something like "Tags" but Adding Dynamic Props might be a solution aswell
Great!
How can we modify collection witch comes from sql server database and show the result in datagrid.
Here i am using ef core and also Community toolkit for using mvvm,
I want to convert the boolean value to Male or Female and show them in dataGrid.
Thanks!
Well actually i use a Select() method that comes from LINQ that method receive a Lambda/Function which you can select how and which columns with an alias you wanna load into the grid, like this.
GRD.DataSource = _MyDbContex.myEntities.(e=> new { FullName = e.Client.Name + " " + e.ClientsLastName, Genre = e.Client.Genre? "Female":"Male"} ).ToList();
what about if i want to create a dynamic object from json response? thanks this video was gold
Yup, you can do that. Thanks for watching
Can you cover integrating Python (CPython) with C# dotnet core? Exchanging pandas dataframes would be nice
I don’t really do python, but it looks pretty easy according to Google 😁
public object [this] seems like black magic to me. Can't say I fully understand the expression, nor that I have ever seen it, but this is interesting. Any hints on what to look up what this exactly is? Thanks :)
It's called an indexer
It's just implementing an indexer for the class just like the one implemented for the Dictionary
@@BrianLagunas Thank you - I'll look into that :)
@@ahmed.adel3 Thanks, Ahmed - I will have a look at this. I never came across those - so, is this something you don't see each day, or am I missing something important about C#?
@@shaihulud4515 From what I saw, yes, people are not using it mush, but I say it is a great feature that will help a lot when you use it for implementing new complex datatypes.
Wow
Thank you
Great Video; can WPF MVVM Re-Size your Main Window from your UserControls
Yes it can.
@@BrianLagunas I try it, can you showme how? please
@@marest7460 Create an attached property and then you'll use it like this prismlibrary.com/docs/wpf/dialog-service.html#style-the-dialogwindow
Hi Brian! It has been seven months since you have posted a Q&A video. Please spare some time.
I know. I have been very busy at work building a brand new product from scratch. It’s taking all my time. I will get back to videos as soon as I can.
@@BrianLagunas Thanks.
You are beautiful!
You’re beautiful too!
I don't like your on the fly naming conventions - very confusing