How to properly initialize a Dictionary in C# with initial values?
Hello everyone! I just started learning C# and ran into a problem when working with dictionaries (Dictionary). I need to create a dictionary that already has some initial values, for example, mappings between country codes and their names.
I know you can do it like this:
```csharp
var countries = new Dictionary();
countries.Add("RU", "Россия");
countries.Add("US", "США");
countries.Add("DE", "Германия");
```
But this takes many lines, especially if there are many values. I heard that in C# there is some shorter syntax for initialization directly when creating the object. I tried writing something like:
```csharp
var countries = new Dictionary
{
"RU" = "Россия",
"US" = "США"
};
```
But it doesn't work — the compiler complains. Please advise.
No answers yet.
Log in to leave an answer
Blogs