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.

TypeName: DoNotAccessListCollectionMultipleTimes
CheckId: SPC050229
Severity: CriticalWarning
Type: AssemblyFileReference
Resolution

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();

Remarks

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.

Links

comments powered by Disqus