Adding Dynamic Properties: ExpandoObject vs DynamicObject

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
well hello there all you beautiful people and thank you for joining me again for another tech question video in this video i'm going to answer a tech question and if you have a tech question you like to have answered make sure you just leave a comment below with your question and i may get to it you don't have to subscribe you don't have to like anything you don't want to click anything just ask your question below and if i know the answer and have time i'll get to it today's question actually doesn't come from a comment on a youtube video or anything like that it actually came from a conversation i was having with a customer now this customer is really struggling with working with dynamic properties what i mean by that is they were dealing with a lot of dynamic data and they they had areas of their application that were pretty dynamic which means that they don't know what these property names or values will be until runtime and so you know they were kind of coming from the uh the javascript world where it's very easy to create dynamic objects with dynamic properties and all this great it's very flexible and dynamic in javascript but what about c sharp you know in this application they have a requirement where they have like dynamic areas of their app so they don't know property names they don't know their values but they need to build up these ui elements based on these these properties and their values and so they are really struggling with how to do this in c sharp how do i build dynamic objects and add properties to these objects dynamically at runtime when you have no idea what these values and property names are going to be well in this video i'm going to show you how to use both the expandable object and a dynamic object and just to kind of drive home the concept we're actually going to be parsing a csv file to a json object well actually a collection of json objects to really demonstrate how powerful these dynamic objects can be let's not wait any longer let's go ahead and get right into the code now the application we are working with today is a very simple.net 5 console application now we want to start adding properties dynamically at runtime in our application for whatever reason now if you were to google this the most popular approach to this you're going to find is using what's called an expando object so let's go ahead and define one of those now we're going to use the dynamic keyword i'm going to call this expando equals new expando object now the dynamic keyword essentially says this object we're creating isn't known until runtime okay we don't know what this is at all it could be anything in this case we're calling in an expando object now an expandable object is just a it's like a property bag okay if we look at this definition we can see that it implements an i collection a key value pair i enumerable uh i dictionary i notified property change so it's essentially a property bag it's a dictionary of properties and actions that we can add so for example i can say hey expando dot first name equals brian and we can write this out we'll say console.writeline expando dot first name now i want to point out because everything is isn't known until runtime you can see when i when i type this out there was no intellisense because we don't know what this object really is okay so i'm going to go ahead and we're going to run this application and we can see oh brian was spit out okay so i was able to to define a property on this expandable object dynamically right uh just just define it just add it to the proper or add it to the object and now i can read that object but what happens if i try to read an object that we haven't defined yet so let's so let's say console.writeline expando dot well we haven't defined this object yet we're not getting in compile errors but we're trying to read it so if we go ahead and run this we're going to see we have an exception okay so that's kind of where you can run into some issues with using expando object and the fact that if you try to use something that hasn't been defined you'll at runtime it'll crash you you won't know until runtime i want to point out i want to get back to this in a minute but i also want to take this moment to point out that you know you can add not only properties but you can add methods as well so for example i can say expando dot i'm gonna call it i don't know invoke equals a new action uh and this action is gonna do something like i don't know uh how about it does console.writeline i did something right and then we can call this as a method on our object and voc right so i dynamically added this method to our property at runtime so brian i did something okay well that's pretty cool so now we're kind of seeing where we can start you know dynamically creating objects that's what this really is you're dynamically creating an object however i don't find this particularly useful in a real world scenario the reason being is most of the time when you're doing something dynamic you don't know what those property names are so you can't define them ahead of time right so for example let's say i just had a string coming from somewhere i don't know where it's coming from but it's called property name and this case is called last name okay and then we have another one coming from somewhere called property value and it equals not a number uh lagoonas okay so we have the property name and the property value coming from somewhere we don't know where it's coming from how do we add this to the expandable object so for example in javascript i could do something like this property name equals property value and then we can say console.writeline expando property name well i can do this in javascript but what happens if we do this here it doesn't work we can't do it this way it completely breaks and this is one of my favorite features of javascript actually when dealing with a lot of dynamic uh dynamic data especially dealing with files now there is a way to kind of do this okay so what i'm going to do i'm going to leave this we can still add properties dynamically to expandable object but we first have to cast that as an i dictionary so i'll just call this dictionary for now equals expando as an i dictionary of string object once you have that cast now you can say hey dictionary i'm going to add something to the dictionary it's going to be the property name and then the property value now we can say console.writeline and we'll say last expandos.last.net because now this has been defined on the object right so let's go ahead and run the application and as you can see brian i did something laguna's this is the this is the gist of creating properties dynamically in c-sharp creating objects dynamically but as you can see there's some limitations here and i'm personally not a big fan of expando object as i said earlier if you googled and did research this is the approach people are going to tell you to use well i want to show you a different approach okay i'm going to comment all this out i want to introduce you to something called a dynamic object now a dynamic object is a base class that you use to derive from to create your own dynamic so for example i'm going to create a class here i'm going to call it dynamic and it's going to derive from dynamic object now i'll have my uh var we'll call it uh dynamic equals new dynamic now what happens if i go to add dynamic dot first name here and we'll say console dot write line uh we say dynamic dot first name and actually i can't call this dynamic i just say dynamic and this can get confusing so i'm going to rename this to something like uh you know let's rename this to dynamic object just to make it a little more clear what's going on here okay so what we want to do first is we want to implement the same kind of behavior of expandable object but what happens when we do this well we get an exception and that's because our dynamic object here doesn't know anything about first name or getting members or anything like that because we're deriving from dynamic object it's our responsibility to control uh the behavior of this object so in order to get the same expando object behavior that we have up above now what i want to do is i'm going to modify our custom object okay so let's go ahead uh i'm going to add let's add a dictionary of string object just like the expando was right i'll just call this dictionary see dictionary equals new dictionary string object now there's two methods that i'm going to want to override here i'm going to override a try get member and i want to override the try set member this essentially is going to tell our dynamic object how to actually treat these members that we're creating okay so in this case i can actually return this i'm going to say return dictionary dot try get value binder dot name and we'll keep the rest the same we're basically going to get this information out of our dictionary so that also means i'm just going to return true here that we want to store these in our dictionary so we can say dictionary index of binder dot name equals value okay so that's all i've done i've just implemented these two methods i'm going to run it and let's see what happens there we go we now have the same behavior of the expando object up here that we that we were playing around with uh but now you're saying well brian i mean what's the point of doing this why can't i looks like expando is still better to use uh yeah i mean we're adding a little bit of code but this provides us more flexibility of how we control the api so for example you know expandable object we have to cast to a dictionary and then call add-off dictionary what if we had a cool little method here void called add property and we just passed a name and value oops forgot to add my object uh now what i can do is i can just kind of cut that out of here and paste that in here modify the code and here we can call add property binder dot name just do a little refactoring here and then value now i can come up here and i can say oh you know what uh dynamic object dot add property last name lagoonis and then let's console.writeline our dynamic object.lastname just so we can see it go ahead and run this application again and as you can see there's brian lagunas now what this essentially does is it allows us to add methods to kind of simplify the api a little bit so instead of casting our expandable object to a dictionary and then adding to the dictionary we can simply just add a method to the object itself called add property and handle it that way so this makes handling those dynamic scenarios where you don't know the property name they're just coming from out of thin air this makes it a lot easier to handle those and to manage that kind of code but i'm going to go back to what i said earlier you know i really like the ability to do something like this right i mean i really really like doing that and so something else that would i would like to be able to do is rightline a dynamic object index of age and read that property out now if we're to do this right now obviously this is going to crash this isn't going to work but because we're using a custom dynamic object guess what we can do we can add a public object this we'll say string index of string uh property name property name okay so we're gonna expose this uh this property if you will we're going to have a getter and we're going to have a setter so if i'm going to get this guess what i can do dictionary index of property name see where i'm going with this oh got to return that and if i'm going to set it guess what how i'm setting it add property property name value right now since we've added this custom code we can now have an api that looks like this so i'm going to go ahead and run this application and here you go brian lagunas 32 so now when you have these properties these property names that are coming from who knows where and you want to you know an easier api to work with this might be an option for you instead of just using expandal object something like this is really nice to work with and it if you're javascript or work in javascript just feels a little more natural coming from the javascript space now what i want to do is i want to show a more real world example of when you even care about this type of dynamic behavior like you're going to say brian when when exactly would i use dynamic properties like this well in a real world scenario uh you might want to parse a file so in this case you know what let's comment this out we don't care about this we'll keep moving on down i have a file here called metalcount.csv and it's just it's a csv file common limited file showing the country and how many gold silver bronze metals they have and the totals of each of those for each country okay these are like the top 25 or something like that so what i want to do is i want to parse this csv file i'm going to convert the csv file into a json object so in order to help achieve that i'm going to use a dynamic object to parse the csv file then i'm going to serialize that dynamic object out into json that's more usable in other places so let's go ahead and get started with that i'm going to create a method called parse csv let's go ahead and define this now the first step to parsing any type of file is we need to actually read the file in so i'm going to say var lines equals i think it's file let's add our system.io read all lines and i'm going to pass in the name which is metal dash count dot c csv next is we need the properties the names of the properties for these objects now these property names are going to be coming from the first line here which is going to be we're going to have a property called country property gold silver bronze total these are our property names so we need those so we'll say property names equals lines index of zero and we want to split those on our comma because it's a comma delimited file now we have these property names what we have to do is we have to loop through all the lines in the uh in the file and then we'll start dynamically creating these objects as we loop through each line okay so we're going to say 4 int x equals 1 because we've already started uh we've we've already parsed that first line okay we'll say x is less than lines dot length and then we'll increment x so now we're going to loop through each of the lines here now we'll start with the current line current line equals lines index of x we're going to split this on the comma as well that's going to give us an array of all the values on that current line and then what we have to do is we're going to have to go through these lines and i see i have a messed up little space there we want to loop through all these values okay so first what we're gonna have to do is we're gonna come up here i'm gonna create a list a list of objects i don't know what kind of objects these are but they're objects these can be the dynamic objects okay so now we have the list of dynamic objects we're looping through each line so now this is where we need to create our dynamic object now if we look up here let's start first we're going to use expando object for this first one so i'm going to create dynamic we'll call it a data object equals new expando object as i dictionary actually let's not even make that dynamic we'll just make that i dictionary just to make it a little easier because now we're working with a dictionary object here otherwise we'd have to cast it so i'm just kind of doing it in one go okay now what we want to do is we're going to say hey for int y equals zero y is less than uh what are we doing here we're going to do properties right less than properties property names because for each object we need to loop through the property names dot length and then we're going to say y plus plus so now we're looping through each of those property lines now we can say okay we need to we need to add these properties to this data object okay so since we have the data object we can just add it and we'll say property names index of y and the value is going to be the current line index of y right makes sense and then after this happens the final step is to add our data objects collection we want to add our data object to our data object collection okay that is a mouthful but this should give you an idea of kind of what's happening here right we're reading all the lines we're getting the property names from the first line then we're going to loop through the remaining lines we're going to start at one for our little incrementer here we're going to get the current line we're going to split it to get an array of all of them now for each property name okay we're going to loop through that we're going to add that property name with its associated value okay so that we're kind of creating that mapping dynamically at runtime now once we have all of these data objects created this is where we can do uh json string equals uh called json serializer i believe uh where what is that called yes it is json serializer right there json.txt dot serialize and then we want data objects then we can console.writeline our json string pretty easy right okay let's go ahead and run the application and see what happens well there there we go there's all our json that was dynamically generated it's kind of hard to read so i'm going to actually fix this just a little bit you can see we can add some json serializer options so i'm going to say new json serializer options okay and then i think there's something with indent yeah right indented equals true perfect so what's that do for us i'm going to run this and now we'll see that all these uh objects the json objects have been written out in a nice formatted manner for us right we could say oh country united states 39 gold 41 silver you get the idea but by using the expando object we were able to dynamically generate all those uh objects coming from the csv file then we can serialize those directly to json not too bad so you know parsing files is an extremely useful scenario for using dynamic objects like expandal object now i do want to go over doing the same thing but using our dynamic object that we've created okay so in this case let's do something a little different we're going to say dynamic data object equals new dynamic whoops dynamic okay so we're going to change a little bit to use our our object now so we'll say we'll change that to add property because we have an add property method we can also do an indexer if we want to do the indexer so now what i'm going to do is we just made that slight change uh now let's run it and see what happens oh well that's very interesting brian why did this happen why all of a sudden do we have no json being generated well when you're using dynamic objects remember you are responsible for everything and so if you take this route there is more responsibility put on you to make sure that you're getting what you want out of dynamic object so in this case we actually have to create a custom json serializer uh which actually it's it's not too bad so let's create a new class i'm gonna call it dynamic uh serializer and this is gonna derive from a json converter actually i don't like that let's call that dynamic converter and this is going to be from a json converter i think that's what it's called converter of t which is the object type in this case dynamic and let's add sterilization and then we'll need to implement the abstract based class so we don't necessarily care about reading in this demo but what i do care about is the right okay so let's go ahead and implement the right now writing this is is very easy as you can see our incoming object to serialize is the dynamic object so we're going to start by using the writer and we're going to write the start object this is essentially the open curly brace and then we want to make sure we have right the end object which is the closing the closing curly brace of our output okay now what we have to do is we have to iterate through each key value pair and write those out in order to do that we need access to this to this dictionary here so i can make this internal for example whoops and then i can do something like this you know for each var key value pair in uh value dot dictionary right so we're going to loop through each of those now we can say writer whoops writer dot write string we want to be able to write the string out and we'll say key value pair dot key and then key value pair dot oops key value pair dot value i'm going to string this now the last step here is we need to tell the serializer to use our our new serializer that we've just created so this is going to be called i think it's converters and this is going to be this is essentially an array of converge or list if you will so you want to make sure that when you define this you can define it easily just like something like this it's really easy to define a list and then i'm going to add our new dynamic converter in here like so and this should be all we need to fix that problem so now now we're getting the same result right we see the same result here everything's the same the only difference here is that because we switched to using the dynamic object that we created and that we're managing because we want to do something special we had to handle the conversion ourselves with a dynamic converter but that's essentially it so i just wanted to make sure that when you're dealing with a dynamic objects you were uh you were knowledgeable about all your options you know you're not stuck with just expandable object and if you are we saw how to use expando object but if you wanted to get you know more complex or you had specialized needs you can create your own dynamic object and then do whatever you want with it create an api that makes sense to you that you can use that you're happy with but just just realize that when you when you go down the the custom route there are some things that you have to take in consideration if you're not converting these to um to json you don't need a dynamic converter but just be aware that when you go the customer out you may need more custom code but that's it for this video i i hope i was able to teach you a little more about dynamic expandable objects and the dynamic dynamic object itself and uh yeah thanks for watching and i will see you in the next video [Music] you
Info
Channel: Brian Lagunas
Views: 1,117
Rating: undefined out of 5
Keywords: adding dynamic properties, dynamic properties, adding dynamic properties in c#, dynamic properties in c#, adding dynamic properties to objects, adding dynamic properties to objects in c#, adding dynamic properties with ExpandoObject, adding dynamic properties with DynamicObject, c# dynamic properties, ExpandoObject, ExpandoObject c#, DynamicObject, DynamicObject c#, convert csv to json, csv to json, Parse csv file, dynamicobject vs expandoobject, csv to json c#
Id: J5YQ8MwMYMw
Channel Id: undefined
Length: 27min 10sec (1630 seconds)
Published: Mon Dec 06 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.