Question3r
Question3r

Reputation: 3742

dictionary default values as parameter

I initialize a dictionary with n keys and zero values. By parameter I can setup some values.

When calling the constructor I execute this

    public Store(Dictionary<int, int> initialItems = null)
    {
        items = new Dictionary<int, int>();

        for (int i = 0; i < 45; i++) // 45 items should exist
        {
            int initialAmount = 0; // 0 as starting value

            if (initialItems != null) // parameter is passed in?
            {
                initialItems.TryGetValue(i, out initialAmount); // start with a higher value than 0
            }

            items.Add(i, initialAmount); // initialize value with 0 or more
        }
    }

    private Dictionary<int, int> items;

I'm asking if this is a good way of passing starting values by parameter. I just want to create a bunch of items and set the value to 0 or a higher value if specified somewhere else, as a constructor parameter for example.

Upvotes: 0

Views: 550

Answers (1)

Access Denied
Access Denied

Reputation: 9461

You can also pass initial dictionary to dictionary's constructor like this:

public Store(Dictionary<int, int> initialItems = null)
{
   if (initialItems!=null)
      items = new Dictionary<int, int>(initialItems);
   else
      items = new Dictionary<int, int>();
   for (int i = 0; i < 45; i++) // 45 items should exist
   {                
     if (!items.ContainsKey(i))
         items.Add(i, 0); // initialize value with 0
   }
}
private Dictionary<int, int> items;

Upvotes: 2

Related Questions