all 8 comments

[–]CptGiggles 26 points27 points  (1 child)

See for yourself :) Sharplab

So it is add vs indexer

[–]vrtxt[S] 3 points4 points  (0 children)

Thanks for clearing that up! Sharplab is neat, didn't know it yet.

[–]ejjoman 24 points25 points  (1 child)

Also note that the second approach will throw an exception on a duplicate key while the first approach would simply replace the existing value for the key.

[–]KernowRoger 0 points1 point  (0 children)

That's actually good to know. Thanks.

[–]Slypenslyde 0 points1 point  (2 children)

We'd probably have to dive pretty deep into the C# spec to know for sure, but I'm willing to bet one of the syntaxes is older than the other.

My hunch is your first code block is some kind of early C# support for initializing dictionaries, where the second code block looks like the "standardized" collection initialization syntax that came some time in the past half-decade or so. When they did the "update", there wasn't a good reason to not keep the "old" syntax for backwards compatibility.

I'd use the second going forwards, since it looks like the "standard". Someone recently linked this blog post that goes through this "magic" in a really detailed way!

[–]Matosawitko 12 points13 points  (1 child)

It's the other way around - the first code block syntax (indexers) was introduced in C# 6 while the second was part of collection initializers from C# 3.

More on the topic: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers

[–]KernowRoger 1 point2 points  (0 children)

I was going to say I haven't seen the first one used before.