Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Collections.Generic.Dictionary `Add` vs set `Item`

If i wish to put items into a System.Collections.Generic.Dictionary, I can either Add or set the Item.

I know if we do Add it checks if the key already exists and if not it throws an exception.

So when adding a ton of items, should I prefer setting Item instead of Add, since Add does unnecessary checks that may actually slow things down?

like image 705
Pacerier Avatar asked May 20 '11 03:05

Pacerier


1 Answers

Here is what happens when you set Item:

public void set_Item(TKey key, TValue value)
{
    this.Insert(key, value, false);
}

Here is what happens when you add item:

public void Add(TKey key, TValue value)
{
    this.Insert(key, value, true);
}

The last parameter last bool add parameter just affects this line:

if (add)
{
    ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
}

So if you want exception when you add a duplicate item, you need to use Add. If you want to overwrite exiting item you need to set Item.

like image 91
Alex Aza Avatar answered Sep 21 '22 06:09

Alex Aza