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
myWeb.Lists["Tasks"].Title = "List_Title";
myWeb.Lists["Tasks"].Description = "List_Description";
myWeb.Lists["Tasks"].Update();
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.
[SuppressMessage("SPCAF.Rules.BestPracticesGroup", "SPC050229:DoNotAccessListCollectionMultipleTimes", Justification = "Provide reason for suppression here")]