Reputation: 25
I am trying to write some code that saves a name and set of records to a text file, and is able to be read and edited. I decided the best way to handle this was by creating a dictionary that held the string variable as the key and the three int variables as its values. However, I cannot get the specific code to work. It says that it cannot hold three values, despite it being declared a list. I have attached the code snippet below. It says the error occurs at the {playerwins, computerwins, ties} part of the dictionary.
private void FileWriter(string playername, int playerwins, int computerwins, int ties)
{
Dictionary<string, List<int>> records = new Dictionary<string, List<int>>()
{
{playername, {playerwins, computerwins, ties } };
}
Upvotes: 2
Views: 214
Reputation: 81523
You can't use a collection initializer like this, you need to specify the actual list type
ie
new List<int>() {playerwins, computerwins, ties}
Fixed example
private void FileWriter(string playername, int playerwins, int computerwins, int ties)
{
var records = new Dictionary<string, List<int>>
{
{playername, new List<int>() {playerwins, computerwins, ties}}
};
}
Another option is to use a Named ValueTuple
var records = new Dictionary<string, (int playerwins, int computerwins, int ties)>
{
{playername, (playerwins, computerwins, ties)}
};
Upvotes: 2