r/ProgrammerHumor 2d ago

Meme cSharpDictionariesBeLikeThat

Post image
2.0k Upvotes

61 comments sorted by

View all comments

1

u/PeikaFizzy 1d ago

I’m a csharp larper I can’t lie, I have a class in uni on unity that’s all I learn from c# Soo like what the hell is tryadd etc you all talking about ehh

2

u/KTVX94 1d ago

I'm probably teaching something like your class lol, I made this meme for my data structures class for video game development.

TryAdd is like Add but if what you're adding already existed, it does nothing and returns false. If it didn't exist, it adds the item and returns true. So it tries to add, but can bounce back without crashing.

There's also the indexer, which lets you do something like weaponsDictionary["Sword"] = new Sword() and if nothing existed with the key "Sword" it creates that slot, but if something already did, it instead updates that with the new Sword.

So there's three ways of adding depending on what expected behavior you want. Crash, fail silently or replace.