Expand Minimize

SPC050229: Do not access SPListCollection by indexer multiple times

Do not access SPListCollection by indexer multiple times. Instantiates the list object only once and assigns it to a variable in order to set properties and call methods.

CheckId SPC050229
TypeName DoNotAccessListCollectionMultipleTimes
Severity CriticalWarning
Type Assembly

Instantiate the list object once and assigns it to a variable in order to set properties and call methods.
Bad Practice

SPWeb myWeb = SPContext.Current.Web;
myWeb.Lists["Tasks"].Title = "List_Title";
myWeb.Lists["Tasks"].Description = "List_Description";
myWeb.Lists["Tasks"].Update();
Good Practice
SPWeb myWeb = SPContext.Current.Web;
SPList myList = myWeb.Lists["Tasks"];
myList.Title="List_Title";
myList.Description="List_Description";
myList.Update();

The rule may lead to false positive results if different lists with the same name are requested in the same method. For instance the statements 'this.Web.Lists["ReusableContent"]' and 'this.Web.Site.RootWeb.Lists["ReusableContent"]' in the same method will be detected as a violation of this rule which is in this case a false positive.

To suppress this violation in managed code add the following attribute to the method which contains the instruction (available since SPCAF version v5.2). Learn more about SuppressMessage here.

// Important: Ensure to have #define CODE_ANALYSIS at the beginning of your .cs file
[SuppressMessage("SPCAF.Rules.BestPracticesGroup", "SPC050229:DoNotAccessListCollectionMultipleTimes", Justification = "Provide reason for suppression here")]
Disclaimer: The views and opinions expressed in this documentation and in SPCAF do not necessarily reflect the opinions and recommendations of Microsoft or any member of Microsoft. SPCAF and RENCORE are registered trademarks of RENCORE AB. All other trademarks, service marks, collective marks, copyrights, registered names, and marks used or cited by this documentation are the property of their respective owners.