BrandGhost

Beginner's Guide To Dictionaries In C# - Get Started NOW!

If you're getting started in C# and your dotnet development, you've probably come across the dictionary class. This video will walk you through the basic usage of dictionaries in C# and is fully intended for beginners! Have you subscribed to my weekly newsletter yet? A 5-minute read every weekend, right to your inbox, so you can start your weekend learning off strong: https://www.devleader.ca/newsletter Check out more Dev Leader content (including full in-depth articles with source code exampl...
View Transcript
regardless of what programming language you start with if you're working with an object-oriented language one of the first things that you start encountering are Collections and there are many different types of collections so even if you're in your algorithms and data structures class you're hearing about Stacks cues arrays lists linked lists you have all these different options and a dictionary or a hash map is one that comes up as well so this video is just going to be a very preliminary look at dictionaries in C sharp so if you're a beginner stay tuned because we're going to walk through some of the basic operations of dictionaries and then a couple of nuances with them as well that you should be able to understand early in your programming journey we'll save the more advanced stuff like concurrent dictionaries and other things for a later time so we're not going to look at the performance or anything fancy for now we're just going to look at the basic operations so you can understand better how to use them in some of your programs alright we'll keep it short and let's jump right into visual studio and get going alright so I'm here in visual studio and on my screen I just have a new project that I created and we can see that from lines eight to ten I have what's is called a record and it's a person type that I've created so there's a name and an age and if you're not familiar with records it's just a really basic class that we have and these are Constructor arguments that also get changed into properties and the other part that I have my program right now is just that I have an array of people so it's a new person array and then I have three people defined in here or three persons however you'd like to go and say that so I just have John who's ages 25 Joe who's age is 26 and Jimmy who's ages 25. now this video is on dictionaries but this is an array of people and I just wanted to start with that so that we could compare the array in the dictionary a lot of the time when we're dealing with things like dictionaries we want to be organizing things by a particular key and then a value so dictionaries are key value stores and the key in a dictionary is supposed to be unique and then the value is something that corresponds to that key so in this example if we wanted to look up the ages for each and individual person what we could do is have a dictionary where the key is the name and then the value is actually the age so instead of an array of them where we would have to go one at a time looking for each name to go pull the age we could actually go look it up very quickly by looking at the particular name and at that position where the name is we pull the age one way that we could do that is actually the code that I have now from line 8 to 13 and this is where we actually declare a dictionary so we have two type parameters because a dictionary in C sharp is what's called a generic so the first type parameter is the string and that's going to be our key and that's because we want the key to be the name and then we have an integer as the second type parameter for the value and that's because it's the age and if you look at the example above in the array you can see that we have a string an integer string and integer and string and integer so that's just to explain how we arrive at this and then we declare the new dictionary I'm just using a short form syntax here because as you can see this part on the left hand side is actually pretty verbose I'm just trying to save some space on the screen this is one type of dictionary initializer that we have access to and I'll show you a couple of variations but in this case we have a key where John is the name and then we have the age 25 being assigned to that key and that corresponds like in the array up above on line three for this entry here the next two for Joe and Jimmy as we see here correspond to the ones we see on line four and five in the array above I've added on screen now another variation of a dictionary initializer and this is extremely similar but instead of having the syntax where we're assigning with the equal side a value to a particular key we're just actually defining the key value pairs themselves inside of the dictionary both of these initializers that I'm showing on screen will result in the exact same behavior for no good reason my personal preference is to use this one above I really like the look of just how having the equal sign and having fewer curly braces but to each their own these will do the exact same thing okay instead if we didn't want to go defining all of the people right when we're creating the dictionary we could go ahead and add these things to the dictionary after it's created the Syntax for being able to do that is what I have on screen right now so from lines 9 to 11 as you can see we're just adding entries into the dictionary if you see on line eight we have the semicolon right at the end so this part actually makes the new dictionary and then these three lines add the items and if you recall what we just had in the video right before this these three things correspond to how we were initializing the dictionary before and they correspond to what we would see in this array otherwise in this case we're using the add method on the dictionary and one of the characteristics of the ad method is that if the item already exists this will throw an exception for us this can be a good and a Bad Thing depending on your program and the types of checks you're doing because a dictionary by definite definition is not supposed to be able to have duplicate keys inside of it so if you accidentally had a duplicate key added like this even if you had a different age assigned to that key this particular line here on line 12 will actually throw an exception because once we've executed line 11 before it we already have this key inside of the dictionary so this will throw a duplicate key exception if we wanted to check if Jimmy was already inside of this dictionary we could write code that looks like this on line 12 now I have this if statement that's saying people by age contains key and then we use Jimmy passed in and this exclamation mark in front actually inverts the rest of this so This actually says if not people by age contains key Jimmy or otherwise said if this dictionary does not contain the key Jimmy then we can go ahead and add it so if this code were to execute line 11 would run and then when line 12 runs it would actually say hey Jimmy's already inside of this dictionary when we use contains key therefore we won't go run this and if we commented out line 11 like this then this code would run on line 12 and say people by age does not contain the key Jimmy therefore we will come into this if statement and add Jimmy an alternative way that we could accomplish this if we just wanted to be able to overwrite what's already in the dictionary is by using the indexer on screen now from lines 9 to 11 I've actually changed the code to instead use the indexer instead of the add method for these three items when we assign them like this this will have the exact same behaviors when we were adding them before because there are no duplicate keys if you think about the other example that we had prior to this when we were trying to add a duplicate with Jimmy as the key in this particular case line 12 will not throw an exception but will instead just overwrite the value one two three for the key Jimmy that means if you're trying to update a dictionary you don't actually have to check if the item exists in the dictionary if your goal is just to overwrite whatever's there already so we've talked a little bit about writing values to the dictionary but if we wanted to get the values back out of the dictionary we could use the indexer as well on lines 13 through 15 I've added three indexers that are actually getting the age for the different keys that we're passing in so John age would end up being assigned to 25 because when it asks the dictionary if John is inside there and pulls the value back out we'll get 25 and the same thing for the other keys but for the other names on line 16 if we had James that we were trying to get out of the dictionary this line 16 would throw an exception when we try to use the indexer with James that's because there is no key in the dictionary with this name using what we learned before we could use contains key first to see if James is in the dictionary before we pull it out so we could try writing an if statement to help us so on line 16 I've added in contains key and we're looking for James and if it is in fact inside the dictionary we can pull it out this is a pretty common type of operation that we might do on a dictionary where we want to be safe and check for a key before we actually go pull the value out and because of that there's actually a better operation that we can use that combines this into one on line 20 I've actually introduced another if statement instead that uses try yet value instead of contains key and try get value will actually return true if the key exists so in this case James and if it does exist it will actually output James age which is the variable we defined using this out parameter if you're not familiar with out parameters this is essentially allowing us to have almost the equivalent to two return values on a method and in later versions of net we actually have some other varieties of ways to do this without the out parameter but one of the common naming conventions and patterns that we have in.net is this try and then some method that we want to be able to try and that pattern is generally a Boolean return value in some out parameter so in this particular case if we were on line 20 because James is not added to the dictionary above here this IFS statement would not actually get entered for the body of it and that's because James when we try to get value would not be found as one of the keys if Instead This was Joe when we go to run line 20 we do know that Joe was inside of the dictionary and that means that Joe Age 2 and I've just made another variable declaration because we already have Joe age up top here but this Joe Age 2 would then get assigned the value of Joe's age and then we would be able to go into this body of the if statement and do something with Joe H2 and because that mostly wraps up the very basic operations of a dictionary I wanted to explain one more slightly Advanced topic because I think that this will come up early in your usage of dictionaries and I thought it would be interesting to cover if you're learning about dictionaries or hash maps in your data structures and algorithms classes what you're going to be noticing is that dictionaries are using hashes to be able to store and look things up so what ends up happening if a hash code for a particular item ends up colliding well I've written the answer right here and essentially you're allowed to have a a duplicate hash code but that's going to end up reducing the performance of a dictionary which is giving us generally this ability to go look up a particular item based on its hash code extremely fast unlike a list where we might have to go look through each element to go find that item but when the hash code is duplicated we end up having a bucket at that particular location inside of the dictionary and the performance ends up falling back to essentially a list so when you have a lot of hash code collisions you end up reducing the performance a great deal again back to a list and that means you're going to have to be iterating internally over the different items in the bucket to pull out what you need so I wanted to illustrate this with a quick example because this is actually something that comes up where people implement this get hash code method incorrectly if you're familiar with record types then you'll know that they have get hash code and equality operators built in for you already out of the box to help a great deal but if you're not familiar you can watch my other video on that to understand that a little bit more clearly when you compare a record and a class now before we had access to records a lot of the time people were implementing their own equality checks and get hash code so that they could compare more complex objects that weren't just a single value so for the example of a person for a person to be equal we might say that the name has to be equal and the age has to be equal as well now in this particular case I'm showing a really bad example so please don't go use this in your code the whole point is to illustrate what happens when we do things wrong so I've actually done a really bad job here on line 23 of making a terrible hash code and we're just using the age it's not even factoring in the other property of the person which is the name so that will mean that just when we have duplicate ages these hash codes are going to collide and if you're thinking about people in general the likelihood that you're dealing with people of the same age is actually pretty high for example statistically a large large majority of the population is below the age 100 and that means that you're going to have billions of people that would fall into that range of below 100 for their age and that means the likelihood of a hash code Collision is really high but just a reminder when the hash code is the same it doesn't mean that the item is going to end up replacing the existing item if we are to assign a new one it just means that the bucket internally inside of the dictionary is going to behave more like a list than it would a dictionary for the fast lookup times if we go back to the example we had at the top this dictionary actually wasn't using the person record at all we had that defined for the array and I just wanted to be able to show you that we could split apart the properties to make a dictionary representing a similar thing if instead we made the person a key this is where we might find some more interesting Behavior with these hash codes colliding so one thing that often happens when we're working with a raise or list and then trying to organize things to go look up by a particular property in this case by name or age this is where we might use something like an array or list list and then use some link or some other operation to convert that into a dictionary so let's quickly look at that and then see what ends up happening when our hash codes Collide all right so on my screen right now I'm actually using what's called link to be able to turn this people array into a dictionary where the key is the person and the value is an integer representing the age of that person now this is a little bit of a contrived example I don't exactly know why you might want to have the entire person as the key for the dictionary but let's go ahead and see what happens just to prove what we have inside of the dictionary when we're done I'm just going to iterate through it and print out all of the items in the dictionary we're using a for each Loop we can use people by age that we're iterating over and then we're going to have a value item for each key value pair inside of there and then we're just using console.writeline to print that out and just a quick reminder we do have two duplicate ages for John and Jimmy both at 25 and if we scroll back down and we look at the get hash code implementation we do act actually have a really poor hash code implementation here just using the age so John and Jimmy should have hash code collisions but we still should see both of them show up in the dictionary okay so when I run the application we can see that we have John Joe and Jimmy printed out as the people this is actually coming from the get hash code call again I wouldn't ever put a console.write lion inside of a get hash code method but you can see that the hash code is 25 for John and then Joe is 26 and Jimmy is also 25 for the hash code and this is because I implemented a really bad hash code method and then if we actually go look at the last three lines that are printed out this is from the for each Loop and we can in fact see that we have a key and a value where the person is the key and the value is the age and we still have John and Jimmy included in here even though their hash codes were the same alright so those are the basics of working with dictionaries inside of C sharp so we looked at being able to initialize dictionaries add things check if things are there and then we looked at updating versus adding as well so if you're just interested in overwriting what's already there you don't necessarily have to check contains key before doing that the last little part that I showed you was something a little bit more advanced but I thought that might be interesting for you to see because if you end up having duplicate entries that are based on the hash code you can see what's going to actually happen inside of your dictionary so remember if the key is the exact same this is where you're going to have that overriding behavior but if the hash code is the same you're still going to have both items show up in the dictionary so it's not going to overwrite what's there but the performance will be reduced we didn't do a benchmark or anything like that but if you had a ton of items and you were looking at the performance with a bad hash code implementation then you would start to see that performance degradation where the dictionary starts behaving like a list so keep that in mind for your data structures and algorithms classes and when you're building software because if you're implementing get hash code and you're doing it wrong you're going to be paying the penalty and performance thanks so much for watching we'll see you next time

Frequently Asked Questions

What is a dictionary in C# and how does it differ from an array?

A dictionary in C# is a key-value store where each key is unique, allowing for quick lookups of values based on those keys. Unlike an array, where you access elements by their index, a dictionary lets you retrieve values using a specific key, making it more efficient for certain operations.

How do I add items to a dictionary in C#?

You can add items to a dictionary using the 'Add' method or by using the indexer. If you use the 'Add' method and try to add a key that already exists, it will throw an exception. If you use the indexer, it will overwrite the existing value for that key if it already exists.

What should I do if I want to check if a key exists in a dictionary before accessing its value?

You can use the 'ContainsKey' method to check if a key exists in the dictionary before accessing its value. Alternatively, you can use the 'TryGetValue' method, which attempts to get the value associated with a key and returns a boolean indicating whether the key was found.

These FAQs were generated by AI from the video transcript.
An error has occurred. This application may no longer respond until reloaded. Reload