Rule Definition
This rule warns about a property accessed inside an iteration statement when the property returns a cloned object. In this case, multiple identical objects are created. If this is not the intent, access the property outside the iteration statement. Otherwise, multiple unnecessary objects are created and afterward, these objects must be garbage collected. This degrades performance, especially in compact iteration statements.
Note that it is possible that such a construct is intended, and in that case this violation is perfectly acceptable like in the following case:
public void BuildArrayOfArrayLists()
{
for(int i = 0; i < arrayOfLists.Length; i++)
{
arrayOfLists[i] = cloner.List;
}
}
Remediation
Whenever possible assign the property to a local variable outside the iteration statement and use the local variable inside the iteration statement.
Violation Code Sample
using System;
using System.Collections;
namespace BankingLibrary
{
public class BankAccounts
{
ArrayList someList = new ArrayList();
public ArrayList List
{
get{ return (ArrayList)someList.Clone(); }
}
public void ModifyList(object anything)
{
someList.Add(anything);
}
}
public class Customer
{
BankAccounts accounts;
ArrayList[] arrayOfLists;
public Customer()
{
accounts = new BankAccounts();
accounts.ModifyList("Money");
arrayOfLists = new ArrayList[10];
}
// VIOLATION
public void CustomerReport()
{
for(int i = 0; i < 10; i++) { Console.WriteLine(accounts.List); }
}
}
}
Fixed Code Sample
using System;
using System.Collections;
namespace BankingLibrary
{
public class BankAccounts
{
ArrayList someList = new ArrayList();
public ArrayList List
{
get{ return (ArrayList)someList.Clone(); }
}
public void ModifyList(object anything)
{
someList.Add(anything);
}
}
public class Customer
{
BankAccounts accounts;
ArrayList[] arrayOfLists;
public Customer()
{
accounts = new BankAccounts();
accounts.ModifyList("Money");
arrayOfLists = new ArrayList[10];
}
// REMEDIATION
public void CustomerReport()
{
ArrayList localAcccounts = accounts.List;
for(int i = 0; i < 10; i++) { Console.WriteLine(localAcccounts); }
}
}
}
Reference
Microsoft Visual Studio 2005 - http://msdn.microsoft.com/en-us/library/ms182270(VS.80).aspx
Related Technologies
.Net
Technical Criterion
Efficiency - Expensive Calls in Loops
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.