3

I searched and got the difference between List.AddItem() and List.Item.Add().

SPList.Add() vs SPList.AddItem() SharePoint 2010

Now the query which comes to my mind is that why Sharepoint has two such methods. The Item.Add() method is in SP2007 and they added the AddItem() in SP2010. Now why they have not marked Item.Add() as depricated one.

We know that Item.Add() is slow in execution as compared to AddItem().Even the MSOCAF tool always throws error for Item.Add() and will force you to change to AddItem().

2
  • If u do not have answer do not put suggestion. Be bold enough to ask any question in ur mind ....will Lead you to success. Its a correct question from SP developer point of view.
    – Pushpendra
    Commented Jul 23, 2013 at 7:16
  • ...I was just politely suggesting that, as suggested from the link you posted, you simply switch to use the new implementation. The difference between the two method have already been explained, so I don't think you should bother asking yourself why two "equivalent" methods exist. That's just IMHO though. Anyway, if it will make you better, I will delete that suggestion. Commented Jul 23, 2013 at 8:23

1 Answer 1

5

When you call SPList.Items.Add() it will fetch all list items through an SPQuery. This can be very costly when you have a considerable amount of items.

// Microsoft.SharePoint.SPList
public SPListItemCollection Items
{
    [ClientCallableExceptionConstraint(FixedId = "c", ErrorType = typeof(SPQueryThrottledException), Condition = "There is a throttle failure.", ErrorCode = -2147024860)]
    get
    {
        return this.GetItems(new SPQuery
        {
            ViewAttributes = "Scope=\"Recursive\""
        });
    }
}

When you call SPList.AddItem() it avoids fetching all items. You'll see in the implementation (code below) that it does a 'trivial' query which basically says "get me all items where ID = -1".

// Microsoft.SharePoint.SPList    
public SPListItem AddItem()
{
    SPQuery query = this.HasExternalDataSource ? SPQuery.TrivialQueryExternalList : SPQuery.TrivialQuery;
    SPListItemCollection items = this.GetItems(query);
    return items.Add();
}

When you're adding an item it makes no sense to first fetch all existing items in the list. The old implementation is preserved for backward compatibility.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.