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
  • НаукаНаука

Комментарии • 91

  • @minitam1527
    @minitam1527 Месяц назад +1

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

  • @AbanoubZak-dq4op
    @AbanoubZak-dq4op Год назад +1

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

  • @kellymurphystl
    @kellymurphystl Год назад +1

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

  • @mochsner
    @mochsner 2 года назад +2

    Very helpful and well worded. Ty!

  • @patoche8135
    @patoche8135 6 месяцев назад

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

  • @NickBullCSharp
    @NickBullCSharp 2 года назад +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

  • @gregorplacht7841
    @gregorplacht7841 2 года назад +1

    Fantastic, you saved me. Thanks a ton!

  • @yaswanthnaveen385
    @yaswanthnaveen385 2 года назад +2

    Fantastic, Saved my day

  • @karlok74
    @karlok74 2 месяца назад

    great tutorial!!!!

  • @MasterRicochet
    @MasterRicochet Год назад +1

    Your're awesome! Thank you

  • @WinneeGustavoCabreraVillamayor
    @WinneeGustavoCabreraVillamayor Год назад +1

    Amazing thanks you so much, greetings from Paraguay

  • @hasandogan3510
    @hasandogan3510 Год назад +1

    Hi Brian! Very good explanation bro thank you!

  • @ahmedayad982
    @ahmedayad982 2 года назад +1

    Great topic, thanks.

  • @AS-kw1ob
    @AS-kw1ob 2 года назад +1

    Great, thank you very much!

    • @BrianLagunas
      @BrianLagunas  2 года назад

      Thanks for watching

    • @AS-kw1ob
      @AS-kw1ob 2 года назад

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

  • @BioExtract
    @BioExtract 2 года назад +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  2 года назад +1

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

  • @arbi4922
    @arbi4922 Год назад +1

    This kind of stuff I need.

  • @midnightloverdog
    @midnightloverdog Год назад +1

    Hi Brian This is really informative.

  • @monicatomar1860
    @monicatomar1860 2 года назад +1

    Thanks alot... Your video saved me 😇

  • @user-zh6pq2ew4n
    @user-zh6pq2ew4n Год назад +1

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

  • @giribad26
    @giribad26 3 месяца назад

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

  • @odahlaurent9309
    @odahlaurent9309 Год назад +2

    Really cool

  • @hussainhussaini2267
    @hussainhussaini2267 2 года назад +2

    I love JObject, JArray, and JToken from NewtownSoft

    • @wgsolutions2760
      @wgsolutions2760 2 года назад +1

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

  • @rliy001
    @rliy001 2 года назад

    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?

    • @BrianLagunas
      @BrianLagunas  2 года назад

      This sounds like a great use of dynamic

  • @charmerpppify
    @charmerpppify Год назад +1

    I miss this videos Brian
    hope u r well

    • @BrianLagunas
      @BrianLagunas  Год назад +1

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

  • @ahmed.adel3
    @ahmed.adel3 2 года назад

    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  2 года назад +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.

  • @pramod.kulkarni9607
    @pramod.kulkarni9607 8 месяцев назад +1

    Was very helpful thanks

  • @AbanoubZak-dq4op
    @AbanoubZak-dq4op Год назад

    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!

  • @ATsidvintsev
    @ATsidvintsev Год назад

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

  • @ministerofrock
    @ministerofrock 2 года назад

    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  Год назад

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

  • @BahawalTV
    @BahawalTV 2 года назад

    What are the benefits of using expando object over dataset?

  • @yevheniytymchishin8401
    @yevheniytymchishin8401 2 года назад +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  2 года назад +1

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

  • @VimalRaj-ki4dg
    @VimalRaj-ki4dg 2 года назад

    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?

  • @mottosson
    @mottosson 2 года назад

    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 2 года назад

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

  • @dasfahrer8187
    @dasfahrer8187 2 года назад

    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  2 года назад +1

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

  • @user-ge2gj2lf4r
    @user-ge2gj2lf4r Год назад

    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?

    • @BrianLagunas
      @BrianLagunas  Год назад

      This is the type of question I get paid to answer 😁

    • @user-ge2gj2lf4r
      @user-ge2gj2lf4r Год назад

      ​@@BrianLagunas thanks ..

  • @rarepanda3766
    @rarepanda3766 2 года назад

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

    • @BrianLagunas
      @BrianLagunas  2 года назад

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

    • @pandalord289
      @pandalord289 2 года назад +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

  • @faisalsadat7118
    @faisalsadat7118 Год назад

    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 8 месяцев назад

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

  • @matiasezequielherrera7327
    @matiasezequielherrera7327 Год назад +1

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

    • @BrianLagunas
      @BrianLagunas  Год назад

      Yup, you can do that. Thanks for watching

  • @joy5087
    @joy5087 2 года назад

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

    • @BrianLagunas
      @BrianLagunas  2 года назад

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

  • @shaihulud4515
    @shaihulud4515 2 года назад +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  2 года назад

      It's called an indexer

    • @ahmed.adel3
      @ahmed.adel3 2 года назад

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

    • @shaihulud4515
      @shaihulud4515 2 года назад

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

    • @shaihulud4515
      @shaihulud4515 2 года назад

      @@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 2 года назад

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

  • @mohammadramezani1233
    @mohammadramezani1233 10 месяцев назад

    Wow

  • @marest7460
    @marest7460 2 года назад

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

    • @BrianLagunas
      @BrianLagunas  2 года назад

      Yes it can.

    • @marest7460
      @marest7460 2 года назад

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

    • @BrianLagunas
      @BrianLagunas  2 года назад +1

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

  • @MuhammadSaleem-qz7xp
    @MuhammadSaleem-qz7xp Год назад

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

    • @BrianLagunas
      @BrianLagunas  Год назад

      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 Год назад

      @@BrianLagunas Thanks.

  • @shinkobayashi5915
    @shinkobayashi5915 11 месяцев назад +1

    You are beautiful!

  • @simonearnshawuk
    @simonearnshawuk 2 года назад +1

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