Adding Dynamic Properties: ExpandoObject vs DynamicObject

Sdílet
Vložit
  • čas přidán 20. 06. 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
  • Věda a technologie

Komentáře • 91

  • @AbanoubZak-dq4op
    @AbanoubZak-dq4op Před rokem +1

    One word, Amazing, I don't have something else that can describe all of this(Experience, Explanations, clarity)

  • @minitam1527
    @minitam1527 Před měsícem +1

    Thank you for this video.. You explained everything so clearly.

  • @kellymurphystl
    @kellymurphystl Před rokem +1

    Great topic, very clearly explained. You have a new subscriber here!

  • @mochsner
    @mochsner Před 2 lety +2

    Very helpful and well worded. Ty!

  • @NickBullCSharp
    @NickBullCSharp Před 2 lety +1

    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

  • @user-zh6pq2ew4n
    @user-zh6pq2ew4n Před rokem +1

    Hi Brian, can you make a video on how to implement a paging collection view in your approach?
    Thanks!

  • @patoche8135
    @patoche8135 Před 6 měsíci

    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. 👍👏

  • @gregorplacht7841
    @gregorplacht7841 Před 2 lety +1

    Fantastic, you saved me. Thanks a ton!

  • @yaswanthnaveen385
    @yaswanthnaveen385 Před 2 lety +2

    Fantastic, Saved my day

  • @hasandogan3510
    @hasandogan3510 Před rokem +1

    Hi Brian! Very good explanation bro thank you!

  • @ahmedayad982
    @ahmedayad982 Před 2 lety +1

    Great topic, thanks.

  • @BioExtract
    @BioExtract Před 2 lety +3

    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

    • @BrianLagunas
      @BrianLagunas  Před 2 lety +1

      Thank you so much. I’m glad I could be helpful

  • @WinneeGustavoCabreraVillamayor

    Amazing thanks you so much, greetings from Paraguay

  • @hussainhussaini2267
    @hussainhussaini2267 Před 2 lety +2

    I love JObject, JArray, and JToken from NewtownSoft

    • @wgsolutions2760
      @wgsolutions2760 Před 2 lety +1

      The best way to go for me too. I like the tutorial about how to use ExpandoObject though.

  • @midnightloverdog
    @midnightloverdog Před rokem +1

    Hi Brian This is really informative.

  • @karlok74
    @karlok74 Před 2 měsíci

    great tutorial!!!!

  • @MasterRicochet
    @MasterRicochet Před rokem +1

    Your're awesome! Thank you

  • @giribad26
    @giribad26 Před 4 měsíci

    Great explanation. Just a quick question, performance wise which is better Dynamic object or ExpandoObject when dealing with large data?

  • @monicatomar1860
    @monicatomar1860 Před 2 lety +1

    Thanks alot... Your video saved me 😇

  • @AS-kw1ob
    @AS-kw1ob Před 2 lety +1

    Great, thank you very much!

    • @BrianLagunas
      @BrianLagunas  Před 2 lety

      Thanks for watching

    • @AS-kw1ob
      @AS-kw1ob Před 2 lety

      @@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?

  • @ahmed.adel3
    @ahmed.adel3 Před 2 lety

    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

    • @BrianLagunas
      @BrianLagunas  Před 2 lety +1

      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.

  • @rliy001
    @rliy001 Před 2 lety

    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?

  • @arbi4922
    @arbi4922 Před rokem +1

    This kind of stuff I need.

  • @ministerofrock
    @ministerofrock Před 2 lety

    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?

    • @BrianLagunas
      @BrianLagunas  Před rokem

      You could build the columns dynamically instead of letting the grid auto discover.

  • @charmerpppify
    @charmerpppify Před rokem +1

    I miss this videos Brian
    hope u r well

    • @BrianLagunas
      @BrianLagunas  Před rokem +1

      All is well. It’s just really hard to find time to record videos.

  • @BahawalTV
    @BahawalTV Před 2 lety

    What are the benefits of using expando object over dataset?

  • @yevheniytymchishin8401
    @yevheniytymchishin8401 Před 2 lety +2

    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.

    • @BrianLagunas
      @BrianLagunas  Před 2 lety +1

      Dictionary does not do the same things as ExpandoObject or DynamicObject.

  • @mottosson
    @mottosson Před 2 lety

    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!

    • @ministerofrock
      @ministerofrock Před 2 lety

      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...

  • @odahlaurent9309
    @odahlaurent9309 Před rokem +2

    Really cool

  • @ATsidvintsev
    @ATsidvintsev Před rokem

    Very Good. But, how can i use DynamicObject for display in PropertyGrid(windows form) and change value? With [Category, DisplayName and so on]? Thanks

  • @dasfahrer8187
    @dasfahrer8187 Před 2 lety

    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?

    • @BrianLagunas
      @BrianLagunas  Před 2 lety +1

      You can dynamically create bindings in code too, plus ExpandoObject implements INotifyPropertyChanged as well 😁

  • @rarepanda3766
    @rarepanda3766 Před 2 lety

    This is an awesome video, could you maybe make an example on how to use Azure Cosmos DB with it?

    • @BrianLagunas
      @BrianLagunas  Před 2 lety

      Hmmmm. I don’t use Azure much but maybe I can do something in the future.

    • @pandalord289
      @pandalord289 Před 2 lety +1

      @@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

  • @VimalRaj-ki4dg
    @VimalRaj-ki4dg Před 2 lety

    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?

  • @AbanoubZak-dq4op
    @AbanoubZak-dq4op Před rokem

    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!

  • @user-ge2gj2lf4r
    @user-ge2gj2lf4r Před rokem

    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?

  • @joy5087
    @joy5087 Před 2 lety

    Can you cover integrating Python (CPython) with C# dotnet core? Exchanging pandas dataframes would be nice

    • @BrianLagunas
      @BrianLagunas  Před 2 lety

      I don’t really do python, but it looks pretty easy according to Google 😁

  • @matiasezequielherrera7327

    what about if i want to create a dynamic object from json response? thanks this video was gold

  • @shaihulud4515
    @shaihulud4515 Před 2 lety +2

    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 :)

    • @BrianLagunas
      @BrianLagunas  Před 2 lety

      It's called an indexer

    • @ahmed.adel3
      @ahmed.adel3 Před 2 lety

      It's just implementing an indexer for the class just like the one implemented for the Dictionary

    • @shaihulud4515
      @shaihulud4515 Před 2 lety

      @@BrianLagunas Thank you - I'll look into that :)

    • @shaihulud4515
      @shaihulud4515 Před 2 lety

      @@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#?

    • @ahmed.adel3
      @ahmed.adel3 Před 2 lety

      @@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.

  • @faisalsadat7118
    @faisalsadat7118 Před rokem

    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!

    • @StevDevOfficial
      @StevDevOfficial Před 8 měsíci

      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();

  • @pramod.kulkarni9607
    @pramod.kulkarni9607 Před 8 měsíci +1

    Was very helpful thanks

  • @marest7460
    @marest7460 Před 2 lety

    Great Video; can WPF MVVM Re-Size your Main Window from your UserControls

    • @BrianLagunas
      @BrianLagunas  Před 2 lety

      Yes it can.

    • @marest7460
      @marest7460 Před 2 lety

      @@BrianLagunas I try it, can you showme how? please

    • @BrianLagunas
      @BrianLagunas  Před 2 lety +1

      @@marest7460 Create an attached property and then you'll use it like this prismlibrary.com/docs/wpf/dialog-service.html#style-the-dialogwindow

  • @mohammadramezani1233
    @mohammadramezani1233 Před 10 měsíci

    Wow

  • @MuhammadSaleem-qz7xp
    @MuhammadSaleem-qz7xp Před rokem

    Hi Brian! It has been seven months since you have posted a Q&A video. Please spare some time.

    • @BrianLagunas
      @BrianLagunas  Před rokem

      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.

    • @MuhammadSaleem-qz7xp
      @MuhammadSaleem-qz7xp Před rokem

      @@BrianLagunas Thanks.

  • @shinkobayashi5915
    @shinkobayashi5915 Před rokem +1

    You are beautiful!

  • @simonearnshawuk
    @simonearnshawuk Před 2 lety +1

    I don't like your on the fly naming conventions - very confusing